[jquery] jQuery hasClass() - check for more than one class

With:

if(element.hasClass("class"))

I can check for one class, but is there an easy way to check whether "element" has any of many classes?

I am using:

if(element.hasClass("class") || element.hasClass("class") ... )

Which isn't too bad, but I am thinking of something like:

if(element.hasClass("class", "class2")

Which unfortunately doesn't work.

Is there something like that?

This question is related to jquery performance jquery-selectors

The answer is


Works for me:

 if ( $("element").hasClass( "class1") || $("element").hasClass("class2") ) {

 //do something here

 }

jQuery

if( ['class', 'class2'].some(c => [...element[0].classList].includes(c)) )

Vanilla JS

if( ['class', 'class2'].some(c => [...element.classList].includes(c)) )

element.is('.class1, .class2')

works, but it's 35% slower than

element.hasClass('class1') || element.hasClass('class2')

enter image description here

If you doubt what i say, you can verify on jsperf.com.

Hope this help someone.


How about this?

if (element.hasClass("class1 class2")

You can do this way:

if($(selector).filter('.class1, .class2').length){
    // Or logic
}

if($(selector).filter('.class1, .class2').length){
    // And logic
}

$.fn.extend({
    hasClasses: function (selectors) {
        var self = this;
        for (var i in selectors) {
            if ($(self).hasClass(selectors[i])) 
                return true;
        }
        return false;
    }
});

$('#element').hasClasses(['class1', 'class2', 'class3']);

This should do it, simple and easy.


filter() is another option

Reduce the set of matched elements to those that match the selector or pass the function's test.

$(selector).filter('.class1, .class2'); //Filter elements: class1 OR class2

$(selector).filter('.class1.class2'); // Filter elements: class1 AND class2

here's an answer that does follow the syntax of

$(element).hasAnyOfClasses("class1","class2","class3")
(function($){
    $.fn.hasAnyOfClasses = function(){
        for(var i= 0, il=arguments.length; i<il; i++){
            if($self.hasClass(arguments[i])) return true;
        }
        return false;
    }
})(jQuery);

it's not the fastest, but its unambiguous and the solution i prefer. bench: http://jsperf.com/hasclasstest/10


This worked for me:

$('.class1[class~="class2"]').append('something');

What about:

if($('.class.class2.class3').length > 0){
    //...
}

use default js match() function:

if( element.attr('class') !== undefined && element.attr('class').match(/class1|class2|class3|class4|class5/) ) {
  console.log("match");
}

to use variables in regexp, use this:

var reg = new RegExp(variable, 'g');
$(this).match(reg);

by the way, this is the fastest way: http://jsperf.com/hasclass-vs-is-stackoverflow/22


What about this,

$.fn.extend({
     hasClasses: function( selector ) {
        var classNamesRegex = new RegExp("( " + selector.replace(/ +/g,"").replace(/,/g, " | ") + " )"),
            rclass = /[\n\t\r]/g,
            i = 0,
            l = this.length;
        for ( ; i < l; i++ ) {
            if ( this[i].nodeType === 1 && classNamesRegex.test((" " + this[i].className + " ").replace(rclass, " "))) {
                return true;
            }
        }
        return false;
    }
});

Easy to use,

if ( $("selector").hasClasses("class1, class2, class3") ) {
  //Yes It does
}

And It seems to be faster, http://jsperf.com/hasclasstest/7


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value