Make jQuery :contains Case-Insensitive

// NEW selector
jQuery.expr[':'].Contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

// OVERWRITES old selecor
jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

Update to work for jQuery 1.8

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

With this in place,

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

would select all three of these elements:

<div>john</div>
<div>John</div>
<div>hey hey JOHN hey hey</div>

Demo via Pablo Fortes.

Comments

  1. Emanuele "ToX" Toscano
    Permalink to comment#

    Some time ago, I found this snippet somewhere on the net:

    $.extend($.expr[":"], {
    "containsNC": function(elem, i, match, array) {
    return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
    });

    I like it better because with this code you leave the :contains selector himself and have a new :containsNC selector, which is case insensitive.


    $("div:containsNC('John')")

    • Jonathan Gravois
      Permalink to comment#

      Very helpful and needed RIGHT NOW by me! My question is WHERE do I put the first part:

      $.extend($.expr[":"], {
      "containsNC": function(elem, i, match, array) {
      return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
      }
      });

      Would that go inside the document ready function? Would it be a separate js file?

      I want to use it in the following function which is in a “(function(){” code block

      $(document).on('keyup', '.rowFilter', function(e){
      var table = $(this).parent().next('table').attr('id');
      var rows = $( '#'+table+' tbody').find('tr').hide();
      var data = this.value.split(" ");

      $.each(data, function(i, v){
      rows.filter(":containsNC('"+v+"')").show();
      });
      });

    • Vladkras
      Permalink to comment#

      +1 for custom selector. Not a good idea to override core behaviour (what if someone relies on case sensivity already on the same project). I choosed “icontains” name from the comment below.

  2. Jimbooooooo
    Permalink to comment#

    This is solid and definitely useful, but I can’t agree with overriding the behavior of a core jquery component. It’s much better to make a new selector named “:icontains” or similar and use that.

    Other than that, thanks! Saved me some time.

  3. Andy Cohen
    Permalink to comment#

    Very useful. I am in agreement with the other folks however, in that it should be a new pseudo selector.

  4. samir
    Permalink to comment#

    Thanks for the post , it helps me a lot , thanks a lot again

  5. GAURAV
    Permalink to comment#

    Nice piece of code. Run with just copy and paste

  6. Cezar Luiz

    Awesome! Very helpful for me :) Thanks

  7. Rafael Paranaiba
    Permalink to comment#

    Very nice, thanks!

  8. nicolas
    Permalink to comment#

    I could not understand the code :(((

    what is “jQuery.expr[‘:’]” ? I can’t find anything about it.

  9. nicolas
    Permalink to comment#

    how do you learn how to use this:

    $.expr[“:”].contains

    ?

  10. caiman
    Permalink to comment#

    amazing trick ! Thanks !

  11. Akin
    Permalink to comment#

    Very useful. Thanks!

  12. Ben Power
    Permalink to comment#

    I liked Emanuele’s solution a lot, because sometimes I need it to be case sensitive. Both very useful though, and both should be standard jQuery functionality.

  13. Pratyusha S
    Permalink to comment#

    Hi Jonathan Gravois: I know its Quite late and Your question might be answered by now. But i thought it would be helpful to others .

    $(document).on(‘keyup’, ‘.rowFilter’, function(e){
    var table = $(this).parent().next(‘table’).attr(‘id’);
    var rows = $( ‘#’+table+’ tbody’).find(‘tr’).hide();
    var data = this.value.split(” “);
    $.extend($.expr[“:”], { “containsNC”: function(elem, i, match, array) { return (elem.textContent || elem.innerText || “”).toLowerCase().indexOf((match[3] || “”).toLowerCase()) >= 0;
    }
    });
    var oObj = $( “:containsNC(‘”+v+”‘)” );
    $.each(data, function(i, v){
    rows.filter(‘”+oObj+”‘).show();
    });
    });

  14. jaycreation
    Permalink to comment#

    Simple and it works perfectly.
    Love it! thanks

  15. Chris Bastable, aka baskey
    Permalink to comment#

    Here’s my method should be quite self ex-planetary.
    We are searching for all “p” elements that contain any case variant of “baskey”.

    var str =$(“p”).text();
    var fnd = str.match(/baskey/gi);
    fnd.forEach(function(a){
    $(“p:contains(“+a+”)”).css({color:”red”});
    });

    :)baskey

  16. James
    Permalink to comment#

    Saved me lots of time. Thanks!

  17. Karan Joisher

    Thanks for this snippet! This is something that should be already included in the core library.

  18. LEONARDO
    Permalink to comment#

    For brazilians users, insensitive case with accents stuff

    Para brasileiros, case insensite substituindo acentos por sem acentos

    Abraços

    $.extend($.expr[":"], {"containsNC": function(elem, i, match, array) {
    return (elem.textContent || elem.innerText || "").replace(/[ãáàäâÃÁÄÂ]/g,'a').replace(/[éèêÉÈÊ]/g,'e').replace(/[íìÍÌ]/g,'i').replace(/[óòôõÓÒÔÕ]/g,'o').replace(/[úùûÚÙÛ]/g,'u').replace(/[ç]/g,'c').toLowerCase().indexOf((match[3] || "").replace(/[ãáàäâÃÁÄÂ]/g,'a').replace(/[éèêÉÈÊ]/g,'e').replace(/[íìÍÌ]/g,'i').replace(/[óòôõÓÒÔÕ]/g,'o').replace(/[úùûÚÙÛ]/g,'u').replace(/[çÇ]/g,'c').toLowerCase()) >= 0;
    

    }

    ecowebdesign . com . br

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```

We have a pretty good* newsletter.