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.
Example
jQuery
Javascript
PHP
JQUERY
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.