Cover Image for jQuery contains() method
100 views

jQuery contains() method

The jQuery contains() method is used to select elements that contain specific text content. It allows you to filter elements based on the text they contain.

Here’s the basic syntax of the contains() method:

$(selector).contains(text)

Parameters:

  • selector: A selector expression used to select the elements you want to filter.
  • text: The text content you want to search for within the selected elements.

Return Value:
The contains() method returns a jQuery object containing the elements that match the condition based on their text content.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery contains() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Orange</li>
    </ul>

    <script>
        $(document).ready(function() {
            // Select list items that contain the text "Banana"
            var selectedItems = $("li:contains('Banana')");

            // Add a class to the selected elements for styling
            selectedItems.addClass("selected");
        });
    </script>

    <style>
        .selected {
            background-color: yellow;
        }
    </style>
</body>
</html>

In this example, we have an unordered list (<ul>) with three list items (<li>), each containing the name of a fruit. We use the contains() method to select list items that contain the text “Banana”. We then add a class called “selected” to these items to apply a yellow background to them.

When you run the code, you will see that the list item with the text “Banana” is highlighted with a yellow background.

The contains() method is useful when you want to find elements that have specific text content. It is commonly used to perform text-based filtering or styling based on the content of elements in the DOM. Keep in mind that the contains() method is case-sensitive, so the text must match exactly. If you need case-insensitive search, you can combine :contains() with other jQuery methods or use a custom filter function.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS