jQuery API

:contains() Selector

contains selector

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

  • text
    A string of text to look for. It's case sensitive.

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 a bare word 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:

Support and Contributions

Need help with :contains() Selector or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to :contains() Selector? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • 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”);

  • Anonymous

    Is there any way to use regular expressions?

    • http://www.learningjquery.com/ Karl Swedberg

      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() );
      });

      • Jan Kreutzfeld

        Well, how about:

        $.expr[':'].regexcontains = function(obj, index, meta, stack){
        return (obj.textContent || obj.innerText || jQuery(obj).text() || '').search(new RegExp(meta[3], “ig”)) >= 0;
        };

  • http://atelier-crisaline.fr/ Loizeau

    Hi,
    I’m search to use this function but I have one problem with a string contains specials caracters.
    I would found elements “” with this string: ” [C]” the caracter ‘[‘ block me !!!

  • http://www.russelluresti.com/ RussellUresti

    Would there be a way to include multiple text strings with this?

    Such as $(“div:contains(‘John’,'Mary’)”)

    This would look for a div containing either “John” or “Mary”?

    Or would you chain them?

    $(“div:contains(‘John’),div:contains(‘Mary’)”)?

    • http://blog.wassupy.com/search/label/Technology Michael Haren
      • Tom

        what if this is a long array ? is there any way to type :contain(array[0])::contain(array[1])…:contain(array[n-1]) ?
        thx!

        • http://blog.wassupy.com/search/label/Technology Michael Haren

          Tom,

          To do something like that I would use the .filter() method with a function passed in. In your function you could have a little javascript to do something like that. If your array Is very big, though, you might want to think about something completely different for performance reasons

          • Tom

            thanks very much for the advice
            i try to replace the like of
            //$('span.name a:contains(“291b”),span.name a:contains(“titita”)').css(“border”, “2px blue solid”);
            with
            var test = function(index)
            {
            var name = ['291b','titita']
            var item = $( this );
            GM_log(item.text);
            for(i=0;i<name.length;++i)<br> {
            if(name[i]==item.text)
            return true;
            }
            return false;
            }
            $('span.name a').filter(test).css(“border”, “2px blue solid”);
            but no success, i guess I got the syntax wrong, but not sure what's the right</name.length;++i)<br>

  • http://twitter.com/gibatronic Gibran

    If you need an exectly match of a term, you may try this one:

    $.expr[":"].econtains = function(obj, index, meta, stack){
    return (obj.textContent || obj.innerText || $(obj).text() || “”).toLowerCase() == meta[3].toLowerCase();
    }

    Example:
    $(“div:econtains('john')”).css({ color: “#F00″ });

    This will only match <div>John</div>, not <div>A. John</div>, neither <div>John 6</div>… just <div>John</div>!

  • dirtybirddesign

    If you were doing an ajax submit and the returned data from the server included a table with a <td>Success</td> how would/would you use :contains as a conditional for a success msg?
    success: function(data) {
    var table = $(data).find('table');
    if (table:contains(“Success”)) {
    $(“#Cancel”).remove();
    $(“#cancelSuccess”).fadeIn(“slow”);
    } else {
    $(“#Cancel”).remove();
    $(“#cancelError”).fadeIn(“slow”);
    }
    }

    doesnt seem to work.

  • John

    Why doesn’t it work with a variable?

    Example:

    $(“div:contains(‘John’)”).css(“text-decoration”, “underline”);
    This works fine.

    var name = “John”
    $(“div:contains(name)”).css(“text-decoration”, “underline”);
    This doesn’t work!

    • http://twitter.com/ben_mathes ben mathes

      This is because you’re putting your variable within a string. What you want to do is:

      $(“div:contains(” + name+ “)”).css(“text-decoration”, “underline”);

      • Viishaal

        Hello I have hit a strange problem, I am passing a string in contains and the jquery library collapses::::Here is the script

        var sent = “Research Fellow at Capital Markets CRC Limited (C”;
        var nodes = $(“p:contains(“+sent+”)”); // get all paragraphs containing the string

        I see the reason as jQuery gets confused by the bracket in the variable sent above and the jQuery command is not interpreted correctly. Is there a way around this?

    • Alex Medeiros

      I fixed this problem using toString() method

      in javascript when you use “text” the js interpreted this creating a String object, then um cause all method of this object. One of this methods is toString which return a pure string.

      and there is other problem with this selector. You have to use ' ' to show the text which you want do search like this.

      with a pure string
      $(“p:contains('John') “)

      so when you use a variable you have to continues using this ' '
      $(“p:contains('” + name + “') “)

      to close try this:
      $(“div:contains('” + name.toString() + “' )”).css(“text-decoration”, “underline”);

  • BigFish47

    Is there any way to combine the exact match function and the case insensitive function?

    $.expr[":"].econtains = function(obj, index, meta, stack){
    return (obj.textContent || obj.innerText || $(obj).text() || “”).toLowerCase() == meta[3].toLowerCase();
    }

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

  • Meysam Masnouri

    Is there any way to select both of thease tags whit “:contains()” Selector?
    “Chad” and “chad”
    I mean no Difference between LowerCase and UpperCase content.

    • Liucheng

      do it like this:
      $(selector).filter(function() {
      return /some regex/.test( $(this).text() );
      });

  • Kulanthaivelu V

    Hello All,
    I have a requirement to highlight dropdownbox colors. If dropdown's selected index is 0. How to achieve this. Any help would be appreciated.
    Thanks in advance.
    Regards,
    Kulanthaivelu.V

    • Dave

      if ($('#dropdownbox').get(0).selectedIndex != 0) { do something; }

      • Dave

        Woops… change != to ==…

        if ($('#dropdownbox').get(0).selectedIndex == 0) { do something; }

  • Viishaal

    Hello I have hit a strange problem, I am passing a string in contains and the jquery library collapses::::Here is the script

    var sent = “Research Fellow at Capital Markets CRC Limited (C”;
    var nodes = $(“p:contains(“+sent+”)”); // get all paragraphs containing the string

    I see the reason as jQuery gets confused by the bracket in the variable sent above and the jQuery command is not interpreted correctly. Is there a way around this?

    • Viishaal

      Consider this, the query also breaks down on
      :::::::::::::::::::::::::::::::::::::::::::::::::::::

      $.expr[':'].icontains = function(obj, index, meta, stack){

      return (obj.textContent.replace(/[[0-9]+]/g, “”) || obj.innerText.replace(/[[0-9]+]/g, “”) || jQuery(obj).text().replace(/[[0-9]+]/g, “”) || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;

      };

      var sent = “The Sun is a G-type main sequence star comprising about 99.8632 of the total mass of the Solar System. It is a near-perfect sphere, with an oblateness estimated at about 9 millionths, which means that its polar diameter differs from its equatorial diameter by only 10 km (6 mi).”;

      var statement = “p:icontains('”+sent+”')”;

      var nodes = $(statement);

      :::::::::::::::::::::::::::::::::::::::::::

      • Viishaal

        If I remove the . in 99.8632 then it works fine :-/

  • Alex Medeiros

    I fixed this problem using toString() method

    in javascript when you use “text” the js interpreted this creating a String object, then um cause all method of this object. One of this methods is toString which return a pure string.

    and there is other problem with this selector. You have to use ' ' to show the text which you want do search like this.

    with a pure string
    $(“p:contains('John') “)

    so when you use a variable you have to continues using this ' '
    $(“p:contains('” + name + “') “)

    to close try this:
    $(“div:contains('” + name.toString() + “' )”).css(“text-decoration”, “underline”);

  • Llarian

    Using jQuery 1.4.2 (and tested with 1.4.4) , If I have:

    condense_test.txt (FILE)

    SampleAggregateFile.txt (FILE)

    SampleDriver.txt (FILE)

    and in my $(document).ready() function, I have:

    $(“p:contains('SampleAggregateFile.txt'):contains('(FILE)')”).css(“background-color”,”red”);

    $(“p:contains('SampleAggregateFile.txt (FILE)')”).css(“background-color”,”green”);

    In IE8: I get green
    In FF3.6, I get red

    It looks like there are already bug reports about this issue, but I thought I'd comment here in case someone else has a similar issue. I used the the “red” version in my code since it works in both IE and FF.

  • http://www.facebook.com/people/Sriraman-Gopalan/100000463874802 Sriraman Gopalan

    Hello Everybody,

    I am stuck with an issue in IE 7. I have the following XML:

    <x>
    <aa>
    <bb>111</bb>
    <cc>222</cc>
    </aa>
    <aa>
    <bb>333</bb>
    <cc>444</cc>
    </aa>
    </x>

    If I run a selector on this XML as follows:
    $(“aa>bb:contains('333')+cc”,$('x')).text()
    Firefox returns 444 whereas in Internet Explorer 7, there is no response.
    Can somebody please tell me what the issue is?