Is there a case insensitive jQuery :contains selector?

Pat picture Pat · Oct 9, 2008 · Viewed 74.9k times · Source

Is there a case insensitive version of the :contains jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?

Answer

Pat picture Pat · Oct 9, 2008

What I ended up doing for jQuery 1.2 is :

jQuery.extend(
    jQuery.expr[':'], { 
        Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0" 
});

This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged.

Edit: For jQuery 1.3 (thanks @user95227) and later you need

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

Edit: Apparently accessing the DOM directly by using

(a.textContent || a.innerText || "") 

instead of

jQuery(a).text()

In the previous expression speeds it up considerably so try at your own risk if speed is an issue. (see @John 's question)

Latest edit: For jQuery 1.8 it should be:

jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});