jQuery :contains() selector uppercase and lower case issue

You can change the .contains filter to be case insensitive or create your own selector.

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

This creates a new selector: icontains (or you could name it insensitive-contains, or whatever suits your fancy).
It’s usage would be the same as contains: $('div:icontains("Stack")'); would match:

<div>stack</div>
<div>Stack</div>
<div>StAcKOverflow</div>

Or override the existing .contains filter:

jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].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>

Leave a Comment