emilolsson
emilolsson

Reputation: 2038

Check if a selector have a certain set of classes

I'm trying to be able to check if a selector have a certain sets of classes.

.hasClass() can only check if the selector has one class. And the .is() selector can look for multiple classes but will return true if the selector have at least one of the classes.

But I wan't to achieve a way to check if a selector have both of the classes, and only if it has both of the classes do action.

Any pointers?

Upvotes: 4

Views: 591

Answers (5)

Gumbo
Gumbo

Reputation: 655845

You can simple list the class names:

.foo.bar.bar

This selector matches any element that has all the classes foo, bar, and baz.

Upvotes: 4

kevingessner
kevingessner

Reputation: 18995

I think $.is('.class1.class2') will do what you want. For example, $('#foo').is('.a.b') returns true for the following div, but $('#foo').is('.a.c') will return false:

<div id="foo" class="a b"></div>

Isn't that what you're looking for?

Upvotes: 2

John Hartsock
John Hartsock

Reputation: 86902

The is() function should work for you.

  • If you have an element and you write is(".foo") then it will return true if foo is present.
  • if you write is(".foo.bar") then it will return true if foo AND bar is present.
  • If you write is(".foo,.bar") then it will return true if foo OR bar is present.

Upvotes: 2

marcgg
marcgg

Reputation: 66535

You could simply do:

var $blah = $("blah");
if($blah.hasClass("test") && $blah.hasClass("othertest")){
 // something
}

... or use a selector

$(".test.othertest");

Upvotes: 1

Jamiec
Jamiec

Reputation: 136239

does $('div.class1.class2') not do what you're after (ie, find any div with class1 and class2)

Upvotes: 1

Related Questions