8

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
}
JLF
  • 2,280
  • 4
  • 28
  • 45
  • 5
    You can try use `$element.is('.foo, .bar')` – Oleksandr T. Jun 11 '15 at 19:30
  • possible duplicate of [JQuery .hasClass for multiple values in an if statement](http://stackoverflow.com/questions/10559153/jquery-hasclass-for-multiple-values-in-an-if-statement) – depperm Jun 11 '15 at 19:31
  • 3
    How do you want to express two contrary expressions with a single expression? Does `$elem.hasClass("foo bar")` mean that it has both classes or one of the classes? How should jQuery know what you want to express if you don't tell it? – Felix Kling Jun 11 '15 at 19:42
  • 1
    Then use e.g `if($element.is('.foo.bar')){...}else if($element.is('.foo, .bar')){...}` – A. Wolff Jun 11 '15 at 19:46
  • so `is()` is more useful than `hasClass()` whenever more than one class or condition is being used? – JLF Jun 11 '15 at 19:49
  • `is()` accept any kind of selector, even a function or matched set of elements. `hasClass()` is just for checking for a specific class. Both methods have their own usage – A. Wolff Jun 11 '15 at 19:51
  • In my scenario I am only using classes so I was attempting to stay within `hasClass()`. But I see because you have to specify the selector is a class using the `.` that it allows you to append classes together like a normal selector, so that's a plus I guess. – JLF Jun 11 '15 at 19:53

2 Answers2

6

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.

Luca Fagioli
  • 12,722
  • 5
  • 59
  • 57
1

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/

Ted Plaisted
  • 121
  • 5