jQuery :contains Selector – Find All Elements in a Web Page using a Specified Text - Making :contains Selector Case Insensitive

← PrevNext →

A few months back I was working on a project, when I came across a situation where I had to look for lines or elements on a web page, which had specified texts in it. For example, a web page traditionally contains many lines of text (contents), carefully embed inside elements, such as a <div> or <p>, and I had to find all the elements that had specific texts in it.

Normally, it would take some time for anyone to figure out the exact locations of the words, if one has to check them all word by word.

A quick search on the net and found a solution in the form of a jQuery Selector called :contains(). It is simple and quick, and more importantly, it solved my problem.

Syntax

$(“:contains(text)”)

Let’s assume you have a series of words (a small paragraph) inside three <div> elements and you are looking for the word project in it. Once found you wish to highlight the contents of the element (in this case the DIV element) that has the word.

Project Management:”
“The primary challenge of project management”
“is to achieve all project goals”

Here’s how you do it using the :contains() selector.

The Code
<html>
<head>
    <title>jQuery contains Selector</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>

<body>
    <div>Project Management:</div>
    <div>The primary challenge of project management</div>
    <div>is to achieve all project goals.</div>
</body>

<script>
    $(document).ready(function () {

        $('div:contains("project")')
            .css('font-family', 'Georgia')
            .css('font-style', 'italic')
            .css('color', '#DD1144');

        // OR,
        $('div:contains("project")').attr('class', 'elements');
    });
</script>
</html>
Try it

Output

Project Management:
The primary challenge of project management
is to achieve all project goals.

The :contain() selector takes a parameter (see syntax above) and the value I have set for the parameter is project. I have placed the text between double quotes (“”), you may add the search text without the quotes.

However, there is a slight problem. Look carefully at the output, the <div> elements, and its contents. I have mentioned the word project three times in all the three elements. However, the selector has missed the first one Project Management. The letter p is in uppercase. The text in jQuery :contains() selector is case sensitive.

Making jQuery :contains() Case Insensitive

It’s a work around using jQuery version 8.1. Pity, there’s hardly any explanation that would help understand this function better.

Let’s re-write the above script along with the case insensitive function.

<script>
    $(document).ready(function () {

        // CASE INSENSITIVE FUNCTION.
        $.expr[":"].contains = $.expr.createPseudo(function (arg) {
            return function (elem) {
                return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
            };
        });

        $('div:contains(project)')
            .css('font-family', 'Georgia')
            .css('font-style', 'italic')
            .css('color', '#DD1144');
    });
</script>

While executing :contains(), it calls the createPseudo() function. The function takes a parameter arg and the value is project. It looks for the text in each element (in our example the elements are <div>). Finally, it converts the contents of the elements to uppercase and returns.

Now, we have an output that makes more sense.

Output

Project Management:
The primary challenge of project management
is to achieve all project goals.

It Affects the Child Elements Too

The text search using :contains() selector affects every child element of the parent, which has the matching word. For example, if you had another <div> or <p> element inside the third <div>, then the CSS declaration would affect the child element too.

<div>is to achieve all project goals.
    <!--THE CHILD ELEMENT-->
    <div style="margin:0 10px;">Thanks for reading.</div>
</div>

Search Multiple Text using :contains()

Similarly, you can search and highlight multiple text values using the selector. Here in this example, I have declared an array and assigned values, which I want the selector to find for me.

The Example
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

    <style>
        .elements 
        {
            color: Green;
        }
    </style>

    <div>Project Management:</div>
    <div>The primary challenge of project management</div>
    <div>is to achieve all project goals.</div>
    <div>Thanks for reading.</div>
</body>

<script>
    $(document).ready(function () {
        var words = ['of', 'for'];
        $(words).each(function () {
            $('div:contains(' + this + ')').attr('class', 'elements');
        });
    });
</html>
Try it

Output

Project Management:
The primary challenge of project management
is to achieve all project goals.
Thanks for reading.🙂.

← PreviousNext →