jQuery API

:contains() Selector

contains selector

version added: 1.1.4jQuery(':contains(text)')

Description: Select all elements that contain the specified text.

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as bare words or surrounded by quotation marks. The text must have matching case to be selected.

Example:

Finds all divs containing "John" and underlines them.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	
<div>John Resig</div>

<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
      
    
<script>
$("div:contains('John')").css("text-decoration", "underline");
    </script>
</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for :contains() Selector below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • Astinus
    Is there any way to use regular expressions?
  • No, not with :contains. You'd need to use .filter() with a function. Something like this:

    $(selector).filter(function() {
    return /some regex/.test( $(this).text() );
    });
  • me
    The :contains() selector is case sensitive!.
    This is my case insensitive version:

    $.expr[':'].icontains = function(obj, index, meta, stack){
    return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
    };

    Example:

    $("div:icontains('John')").css("text-decoration", "underline");