• jQuery Video Tutorials

jQuery :contains() Selector



The :contains() selector in jQuery is used to select elements that contain a specified string of text. The text to be matched is case-sensitive, which means both "Hello" and "hello" are not considered the same. It selects elements that contain the specified text anywhere within their content, including child elements.

Syntax

Following is the syntax of :contains selector in jQuery −

$(":contains(text)")

Parameters

The "text" is a string to search for within the elements. This string is case-sensitive.

Example 1

In the following example, we are using the :contains selector to highlight the paragraphs containing the word "Tutorialspoint" −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:contains('Tutorialspoint')").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>Tutorialspoint.</p>
    <p>This one will not be highlighted.</p>
    <p>Tutorialspoint.</p>
</body>
</html>

After executing the above program, all the <p> elements that has "Tutorialspoint" word in it will be highlighted with yellow background color.

Example 2

In this example, we are selecting the "List Items" containing a specific text "item" −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li:contains('item')").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>This is the first item.</li>
        <li>Another list item.</li>
        <li>This will not change (background-color will not be added).</li>
        <li>Final item in the list.</li>
    </ul>
</body>
</html>

When we execute the above program, all the list items that has the word "item" in it will be highlighted with yellow background color.

Example 3

In this example, we are selecting the <div> elements that have "Tutorialspoint" text inside them −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("div:contains('Tutorialspoint')").css("font-weight", "bold");
        });
    </script>
</head>
<body>
    <div>I work in Tutorialspoint.</div>
    <div>This will not be bold.</div>
    <div>Tutorialspoint is in Hyderabad.</div>
</body>
</html>

After executing the above program, <div> elements that have "Tutorialspoint" text inside them will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements