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.

Comments

  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

    ReplyDelete
    Replies
    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.

      Thanks

      Delete
  2. nw i used the program and gt the java case insensitive it is easy to understand
    http://www.besanttechnologies.com

    ReplyDelete
  3. Casino Review, Ratings, Games, & Facts
    Casino is a top-notch casino in 암호화폐란 the United States that offers high-quality games, 생활바카라 a vast collection of slot machines, 벳익스플로어 a huge jackpots, and a great  Rating: 3 · 윈 조이 포커 ‎Review by American Gambler bet

    ReplyDelete

Post a Comment

Popular posts from this blog

Jquery 'On' (Events,Direct ,Delegated)

jquery attr() vs prop() (difference)

jQuery popup (dialog) form validation on a normal button click