JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" id="searchText" />
<div id="container">
<ul>
<li><label><input type="checkbox" />Label number two</label></li>
<li><label><input type="checkbox" />Label number three</label>
<ul>
<li><label><input type="checkbox" />Label number two</label></li>
<li><label><input type="checkbox" />Label number three</label></li>
<li><label><input type="checkbox" />Label number four</label></li>
<li><label><input type="checkbox" />Label number five</label></li>
<li><label><input type="checkbox" />Label number six</label></li>
</ul>
</li>
<li><label><input type="checkbox" />Label number four</label></li>
<li><label><input type="checkbox" />Label number five</label></li>
<li><label><input type="checkbox" />Label number six</label></li>
</ul>
</div>
CSS
.highlight {
color: #0095DA;
}
JavaScript
function escapeRegExp(str) {
str = str || '';
return str.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1');
}
$.fn.nonEmptyChildTextNodes = function() {
return this.contents().filter(function() {
return (this.nodeType == 3) && (this.textContent.trim() != '');
});
};
$.fn.wrapText = function(matchText, className) {
if (this.length) {
this.children().wrapText(matchText, className);
this.nonEmptyChildTextNodes().each(function() {
var $textNode = $(this),
text = $textNode[0].textContent,
regExp = new RegExp(escapeRegExp(matchText), 'gi');
var result = regExp.exec(text);
if (result !== null) {
var $elements = $(),
startIndex = 0;
while (result !== null) {
$elements = $elements.add(document.createTextNode(text.slice(startIndex, result.index)));
$elements = $elements.add($('<span></span>').addClass(className).text(result[0]));
startIndex = regExp.lastIndex;
result = regExp.exec(text);
}
$elements = $elements.add(document.createTextNode(text.slice(startIndex)));
$textNode.replaceWith($elements);
}
});
}
return this;
};
$.fn.unwrapText = function(className) {
var $wrappers = this.find('.' + className),
$parents = $wrappers.parent();
$wrappers.replaceWith(function() {
return $(this).text();
});
$parents.each(function() { this.normalize(); });
return this;
};
var className = 'highlight',
$container = $('#container');
$('#searchText').keyup(function() {
var searchText = $(this).val();
$container.unwrapText(className);
if (searchText) {
$container.wrapText(searchText, className);
}
});