jQuery – Search text in the Element with :contains() Selector

The :contains() is a jQuery selector that allows us to search text within the element and select it and perform an action on it.

For example – you are dynamically listing records from the MySQL database table here, you have a requirement to add a search filter based on keypress. In case you can use jQuery AJAX which requests and load data from the server every time when the user press key in the search field.

You can simplify this with :contains() jQuery selector to filter data on the Client side.

There are some other ways in jQuery by which you can do the same operation. But, in this tutorial, I explain how you can use :contains() selector for search text.

Note – The :contains() by default performs case-sensitive search. In the example, I show how you can use for case-sensitive and case-insensitive search.

jQuery - Search text in the Element with :contains() Selector


Table of Content

  1. jQuery :contains()
  2. Create HTML Layout
  3. Search Text in Container
  4. With specific class in Container
  5. Case-insensitive using :contains()
  6. Conclusion

1. jQuery :contains()

It selects the element which contains the specified value.

Syntax –

$(  ":contains( 'search text' )" );

Example 

$( "div:contains( 'hello' )" )

2. Create HTML Layout

I have created post list where the input field is for search text and the <div class='content'> element which contains <div class='title'> and a <p> element.

Full Code

<div class='container'>

    <!-- Search control -->
    <div>
        <input type='text' id='search' placeholder='Search Text'>
    </div>

    <!-- Content list -->
    <div class='content'>
        <div class='title'>
            <a href='https://makitweb.com/dynamically-add-and-remove-element-with-jquery/' >
            Dynamically add and remove element with jQuery
            </a> 
        </div>
        <p>In this post, I show how you can add and remove new element within your web page with jQuery...</p>
    </div>

    <div class='content'>
        <div class='title'>
            <a href='https://makitweb.com/how-to-delete-value-from-array-in-javascript/'>
            How to Delete a value from an Array in JavaScript
            </a>
        </div>
        <p>There are many cases when we have to remove some unused values from the Array which no longer needed within the program...</p>
    </div>

    <div class='content'>
        <div class='title'><a href='https://makitweb.com/read-and-get-parameters-from-url-with-javascript/'>Read and Get Parameters from URL with JavaScript</a></div>
        <p>If you are familiar with PHP where for reading parameters from URL you can use either $_GET or $_REQUEST which take the name of the argument and return value of it...</p>
    </div>

    <div class='content'>
        <div class='title'>
            <a href='https://makitweb.com/html-how-to-show-text-above-image-on-hover/'>
            HTML – How to Show Text Above Image on Hover
            </a>
        </div>
        <p>In this quick tutorial, I show How you can show text above Image when the user hovers the image using only HTML and CSS, no jQuery and JavaScript...</p>
    </div>
 
</div>

The first start with a basic example, where I search input text within the <div class='content'> container if the text is available then show otherwise hide containers.

Full Code

$(document).ready(function(){
    $('#search').keyup(function(){
 
        // Search text
        var text = $(this).val();
 
        // Hide all content class element
        $('.content').hide();

        // Search and show
        $('.content:contains("'+text+'")').show();
 
    });
});

View Demo


4. With specific element in Container

Now search for child elements with the specific class.

Full Code

$(document).ready(function(){
    $('#search').keyup(function(){
 
        // Search text
        var text = $(this).val();
 
        // Hide all content class element
        $('.content').hide();

        // Search 
        $('.content .title:contains("'+text+'")').closest('.content').show();
 
    });
});

The above code searches the input value in title class if it finds then show the parent container.

View Demo


5. Case-insensitive search using :contains()

# Example 1

$(document).ready(function(){
    $('#search').keyup(function(){
 
        // Search text
        var text = $(this).val();
 
        // Hide all content class element
        $('.content').hide();

        // Search 
        $('.content .title:contains("'+text+'")').closest('.content').show();
 
    });
});

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

# Example 2

Loop all .content class and search text with indexOf().

$(document).ready(function(){
    $('#search').keyup(function(){
 
        // Search text
        var text = $(this).val().toLowerCase();
 
        // Hide all content class element
        $('.content').hide();

        // Search 
        $('.content .title').each(function(){
 
            if($(this).text().toLowerCase().indexOf(""+text+"") != -1 ){
                 $(this).closest('.content').show();
            }
        });
    });
});

Both give the same output –

View Demo


6. Conclusion

Using the :contains() selector simplifies the selection process when you’re searching for a value within an element and need to take action on it. Actions may include updating CSS styles, adding or removing CSS classes, or removing elements altogether.

If you found this tutorial helpful then don't forget to share.