JSFiddle - React, Tailwind, and code Playground
by jasonwilczak
HTML
<div id="divtext"><span id="spantext" class="JQsearchable">J A Wilczak</span>
<div><span id="spantext" class="JQsearchable">J A Wilczak</span></div></div>
<div id="divtext2"><span id="spantext" class="JQsearchable">R Wilczak</span>
<div><span id="spantext" class="JQsearchable">R Wilczak</span></div></div>
<button id="btn">Click</button>
CSS
.searchedText {
color: blue;
}
JavaScript
$(document).ready(function () {
$('#btn').click(function () {
wrapWordsBySelector($('#divtext'),['j','a']);
wrapWordsBySelector($('#divtext2'),['j','a']);
});
});
function wrapWordsBySelector(selector, wordArray) {
if (selector === null || selector === undefined || selector.length === 0) {
return;
}
//for all the words in the array that are within the selector that contains the JQsearchable class,
// wrap them in a span so they take on bolds and highlights
var tagPrefix = '<span class="searchedText">'; //will replace the placeholderPrefix once all matches are found
var tagSuffix = '</span>'; //will replace the placeholderSuffix once all matches are found
var placeholderPrefix = '<^>';
var placeholderSuffix = '<$>';
$(selector).each(function () {
$(this).find('.JQsearchable').each(function () {
var html = $(this).text();
for (var i = 0, len = wordArray.length; i < len; i++) {
if (wordArray[i].length > 0) {
var word = wordArray[i].replace(/\W/g, "\\$&");
var re = new RegExp(word, "gi");
if (html.match(re) !== null) {
html = html.replace(re, placeholderPrefix + '$&' + placeholderSuffix);
}
}
}
html = html.split(placeholderPrefix).join(tagPrefix);
html = html.split(placeholderSuffix).join(tagSuffix);
$(this).html(html);
});
});
}