Reputation: 2360
I want to check if an element has this class or another class like this:
if ( $elem.hasClass("foo") || $elem.hasClass("bar") ) {
// do something
}
And I also want to check if an element has two classes:
if ( $elem.hasClass("foo") && $elem.hasClass("bar") ) {
// do something else
}
Is there a way to do this all within the hasClass()
function? Something like:
if ( $elem.hasClass("foo bar") ) {
// do something when element has both classes
}
else if ( $elem.hasClass("foo","bar") ) {
// do something when element has either class
}
Upvotes: 8
Views: 3175
Reputation: 13349
Strictly answering to your question: no, you can not.
hasClass()
accepts a single argument.
As pointed out by others, you might use is()
, but here is a test that shows that performances are very much penalized.
I suggest you to stay with your current code.
Upvotes: 7
Reputation: 121
You could do something a little different to accomplish this. Not sure if this meets your needs though.
Example of something like this:
$("span.foo, span.bar").each( function() {
$(".test").html("foo or bar was found");
});
JS Fiddle: http://jsfiddle.net/s3gL5pwm/1/
A second solution that uses if would be to use .is() instead.
For example:
if ($("span").is(".foo, .bar")) {
$(".test").html("foo or bar exists");
};
JSfiddle: http://jsfiddle.net/eL2a8smt/
Upvotes: 1