public
Last active

Improved jQuery :contains() selector

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/* jQuery selector to match exact text inside an element
* http://wowmotty.blogspot.com/2010/05/jquery-selectors-adding-contains-exact.html
* :containsExact() - case insensitive
* :containsExactCase() - case sensitive
* :containsRegex() - set by user ( use: $(el).find(':containsRegex("/(red|blue|yellow)/gi")') )
*/
$.extend( $.expr[":"], {
containsExact: $.expr.createPseudo ?
$.expr.createPseudo(function(text) {
return function(elem) {
return $.trim(elem.innerHTML.toLowerCase()) === text.toLowerCase();
};
}) :
// support: jQuery <1.8
function(elem, i, match) {
return $.trim(elem.innerHTML.toLowerCase()) === match[3].toLowerCase();
},
 
containsExactCase: $.expr.createPseudo ?
$.expr.createPseudo(function(text) {
return function(elem) {
return $.trim(elem.innerHTML) === text;
};
}) :
// support: jQuery <1.8
function(elem, i, match) {
return $.trim(elem.innerHTML) === match[3];
},
 
containsRegex: $.expr.createPseudo ?
$.expr.createPseudo(function(text) {
var reg = /^\/((?:\\\/|[^\/])+)\/([mig]{0,3})$/.exec(text);
return function(elem) {
return reg ? RegExp(reg[1], reg[2]).test($.trim(elem.innerHTML)) : false;
};
}) :
// support: jQuery <1.8
function(elem, i, match) {
var reg = /^\/((?:\\\/|[^\/])+)\/([mig]{0,3})$/.exec(match[3]);
return reg ? RegExp(reg[1], reg[2]).test($.trim(elem.innerHTML)) : false;
}
 
});

Updated to use innerHTML to prevent matches on nested tags

Added a ":containsRegex" selector which also allows you to add flags. See this demo page.

Updated again with a note about double escaping any regex and added a check on the "reg" variable in case it is null.

Updated to work with jQuery 1.8 changes. Note that the :containsRegex() selector will now need quotes around the regex

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.