JSFiddle - React, Tailwind, and code Playground

by Roman

HTML

<div id="anothercontainer">
    <div>not me</div>
    <div>has one here</div>
    <div>but not here</div>
    <ul>
        <li>this has "has" in it</li>
        <li>this doesn't</li>
        <li>has this one?</li>
        <li>not this one</li>
    </ul>
</div>
<hr>Stuff below here is ignore because it's not in #anothercontainer<hr>
<div id="container">
    <div>even though there's a has, it will only work with #anothercontainer</div>
    <ul>
        <li>has</li>
        <li>don't have</li>
    </ul>
</div>

JavaScript

// Escape all RegEx reserved characters from string
function escRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

// Return matched elements based on regex contents
function highlight(regex, element, child) {
    // Create a regex based on the bot match string
    var regex = new RegExp(escRegExp(regex), 'gim');
    // Generate results based on regex matches within match_parent
    var results = [];
    // Check for element
    if($(element).length) {
        // Match regex on parent element
        var match = $(element).text().match(regex);
        if(match != null) {
            // Push our matches onto results
            $(element).find(child).each(function(index, value) {
                // Push child onto to results array if it contains our regex
                if($(this).text().match(regex)) results.push($(this));
            });
        }
    }
    return results;
}

// Get results example usage
var results = highlight('has', '#anothercontainer', 'div, li');
// Make them sexy and pink
$.each(results, function() {
    $(this).css({color: 'pink'});
});