Javascript

Searching Text Inside Nested Divs Using jQuery and Adding a Class to the Parent Element

Javascript

Searching Text Inside Nested Divs Using jQuery and Adding a Class to the Parent Element

Hey fellow developers! 🤗 Today, I want to share with you a handy jQuery technique to search for specific text inside nested <div> elements, regardless of the depth, and dynamically add a class to the parent element. Let's get right into it! 🚀

Let's dive right into the example:

Assume we have the following HTML structure:

<div class="container">
    <div>
        <p>Some random text here</p>
    </div>
    <div>
        <span>This is the text we want to find</span>
    </div>
    <div>
        <ul>
            <li>
                <p>Nested text inside an unordered list</p>
            </li>
            <li>
                <p>This is the text we want to find</p>
            </li>
        </ul>
    </div>
</div>

Now, let's write the jQuery code to achieve our goal:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    // The text we want to search for
    var searchText = "This is the text we want to find";

    // Find all elements containing the search text
    var elementsWithText = $("div:contains('" + searchText + "')");

    // Add a class to the parent element of each matched element
    elementsWithText.each(function() {
        var parentElement = $(this).parents('div').first();
        parentElement.addClass("highlighted");
    });
});
</script>

In this example, we use the :contains selector to find all <div> elements that contain the specified searchText. Then, we iterate over the matched elements using .each() and add the class "highlighted" to their parent <div> elements using .addClass().

Now, let's add some CSS to style the highlighted elements:

<style>
.highlighted {
    background-color: yellow;
    /* Add any other styles you want to apply */
}
</style>

Voilà! After executing this code, any <div> element that contains the text "This is the text we want to find" will have the "highlighted" class applied, and its background color will turn yellow. You can adjust the CSS class styles to suit your requirements.

Feel free to try out this code snippet on your projects, and let us know if you find it useful! Happy coding! 😄🚀