jQuery: the contains() selector

The jQuery's :contains(search) selector is a powerful feature that can actually enhance our ability to perform text searches. For example, given the following HTML:

<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>

We want to add a CSS class only to the list item that contains the word "one". Here's how it can be done:

$(document).ready(function() {

    $('body > ul').find('li:contains("one")').addClass('one');
    
});

As you can see, this selector comes attached to the element that is supposed to contain a given text. Below you can see the results.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.