Friday, May 3, 2013

Jquery :contains and making it Case-Insensitive

Well, playing around with jQuery, I once came accross jquery contains(). Very handy selector and easy to use and I have been using this in most of my scripts. So what does :contains do..
jQuery( ":contains(text)" );
Jquery contains selects all elements that contains the specified text.
As the doc say, it selects all the elements which contains the given text. the elements can appear directly within the selected element, in any of that element's descendants, or a combination thereof.
try it in fiddle

The above script, will change the color of "Javascript" and "JQUERY". however, if you notice, the color of "jQuery" is not changed, though it starts with `J`. thus, :contains is case sensitive. The text must have matching case to be selected. What is you need contains with Case-Insensitive.

One way to do this is , extending the old :contains selector.
   // OVERWRITES old selecor
jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
However, this overwrites the old contains selector.

OR create a New one
$.extend($.expr[":"], {
"containsIN": function(elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
Now, you can use :containsIN instead of :contains and get the elements
Try it in Fiddle

Some more example to highlight the cells of table which contains the typed letter in input element.


  1. jQuery.expr[':'].contains = function(a,i,m){return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0; // ==0 for exact match

    where to put this code

    1. hello Vivek!

      it is better if you add this to seperate js file , and load it in you html head tag . however adding this code just before your `:contains` selector should work.

      you just have to make sure, the .extend is called before your selector.


  2. nw i used the program and gt the java case insensitive it is easy to understand

  3. I'm very glad when read your article. It's easy to understand and very useful for newbie as me. Thank you so much and wish you happy…Professional Android Training in Chennai

  4. Thanks for sharing beautiful article..check out this website Aurelius corporate training institute made on PHP.