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. User Avatar
    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')")

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

    • User Avatar
      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.

    • User Avatar
      Alexis
      Permalink to comment#

      Thanks! This was really useful and worked like a charm (Y)

  2. User Avatar
    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. User Avatar
    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. User Avatar
    samir
    Permalink to comment#

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

  5. User Avatar
    GAURAV
    Permalink to comment#

    Nice piece of code. Run with just copy and paste

  6. User Avatar
    Cezar Luiz

    Awesome! Very helpful for me :) Thanks

  7. User Avatar
    Rafael Paranaiba
    Permalink to comment#

    Very nice, thanks!

  8. User Avatar
    nicolas
    Permalink to comment#

    I could not understand the code :(((

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

  9. User Avatar
    nicolas
    Permalink to comment#

    how do you learn how to use this:

    $.expr[“:”].contains

    ?

  10. User Avatar
    caiman
    Permalink to comment#

    amazing trick ! Thanks !

  11. User Avatar
    Akin
    Permalink to comment#

    Very useful. Thanks!

  12. User Avatar
    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. User Avatar
    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. User Avatar
    jaycreation
    Permalink to comment#

    Simple and it works perfectly.
    Love it! thanks

  15. User Avatar
    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. User Avatar
    James
    Permalink to comment#

    Saved me lots of time. Thanks!

  17. User Avatar
    Karan Joisher

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

  18. User Avatar
    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

  19. User Avatar
    Himanshu Jain
    Permalink to comment#

    Great post.
    Is there any way to use it in Node.js cheerio.
    I get the error TypeError: Cannot read property ‘:’ of undefined

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag