Code Snippet
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;
};
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.
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')")
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.
Very useful. I am in agreement with the other folks however, in that it should be a new pseudo selector.
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.