Check if the selector has a specific set of classes

I am trying to check if a selector has certain sets of classes.

.hasClass () can only check if the selector has one class. And the .is () selector can search for several classes, but returns true if the selector has at least one of the classes.

But I could not find a way to check if the selector has both classes, and only if it has both classes. Act

Any pointers?

+4
source share
5 answers

You can simply name the class names:

.foo.bar.bar 

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

+4
source

The is () function should work for you.

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

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

 <div id="foo" class="ab"></div> 

Isn't that what you are looking for?

+2
source

does $('div.class1.class2') not do what you need (i.e. find any div with class1 and class2)

+1
source

You can simply do:

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

... or use the selector

$(".test.othertest");

+1
source

Source: https://habr.com/ru/post/1307353/


All Articles