JLF
JLF

Reputation: 2360

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
}

Upvotes: 8

Views: 3175

Answers (2)

Luca Fagioli
Luca Fagioli

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

Ted Plaisted
Ted Plaisted

Reputation: 121

You could do something a little different to accomplish this. Not sure if this meets your needs though.

  1. Use multiple selectors you can see if an element that matches exists on the page
  2. Use each to execute the code you want

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

Related Questions