JQuery .hasClass for multiple values in an if statement

I have a simple if statement as such:

if ($('html').hasClass('m320')) {

// do stuff 

}

This works as expected. However, I want to add more classes to the if statement to check if any of the classes are present in the <html> tag. I need it so it's not all of them but just the presence of at least one class but it can be more.

My use case is that I have classes (e.g. m320, m768) added for various viewport widths so I only want to execute certain Jquery if it's a specific width (class).

Here is what i have tried so far:

1.

if ($('html').hasClass('m320', 'm768')) {

// do stuff 

}

2.

if ($('html').hasClass('m320')) || ($('html').hasClass('m768')) {

 // do stuff 

}

3.

 if ($('html').hasClass(['m320', 'm768'])) {

 // do stuff 

    }

None of these seem to work though. Not sure what I am doing wrong but most likely my syntax or structure.


You could use is() instead of hasClass():

if ($('html').is('.m320, .m768')) { ... }

You just had some messed up parentheses in your 2nd attempt.

var $html = $("html");

if ($html.hasClass('m320') || $html.hasClass('m768')) {

  // do stuff 

}

For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:

$.fn.hasAnyClass = function() {
    for (var i = 0; i < arguments.length; i++) {
        if (this.hasClass(arguments[i])) {
            return true;
        }
    }
    return false;
}

Then, in your example, you could use this:

if ($('html').hasAnyClass('m320', 'm768')) {

// do stuff 

}

You can pass as many class names as you want.


Here's an enhanced version that also lets you pass multiple class names separated by a space:

$.fn.hasAnyClass = function() {
    for (var i = 0; i < arguments.length; i++) {
        var classes = arguments[i].split(" ");
        for (var j = 0; j < classes.length; j++) {
            if (this.hasClass(classes[j])) {
                return true;
            }
        }
    }
    return false;
}

if ($('html').hasAnyClass('m320 m768')) {
    // do stuff 
}

Working demo: http://jsfiddle.net/jfriend00/uvtSA/


This may be another solution:

if ($('html').attr('class').match(/m320|m768/)) {  
  // do stuff   
}  

according to jsperf.com it's quite fast, too.


For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf

In short, using element.hasClass('class') is the fastest.

Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.

The worst performance by far was using element.is('.class').

Also listed in the jsperf is CyberMonk's function, and Kolja's solution.