Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If element has "class1" and/or "class2" in Jquery .hasClass() function

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
}
like image 830
JLF Avatar asked Jun 11 '15 19:06

JLF


1 Answers

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.

like image 148
Luca Fagioli Avatar answered Sep 20 '22 21:09

Luca Fagioli