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开发者_JS百科 action.
Any pointers?
You can simple list the class names:
.foo.bar.bar
This selector matches any element that has all the classes foo, bar, and baz.
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.
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?
does $('div.class1.class2')
not do what you're after (ie, find any div with class1 and class2)
You could simply do:
var $blah = $("blah");
if($blah.hasClass("test") && $blah.hasClass("othertest")){
// something
}
... or use a selector
$(".test.othertest");
精彩评论