views:

63

answers:

5

Hello

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?

+1  A: 

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

Jamiec
I don't see how that relates to `hasClass`, `is`, and similar use cases...
T.J. Crowder
Jamiec
@Jamiec: We're reading the question differently. I'm reading it that he already has the thing (presumably as the result of some other operation) and now wants to test it for a combination of classes, *not* that he wants to go get it.
T.J. Crowder
I'm in an each loop and need to check if $(this) selector have the classes that is stored in an array..
emilolsson
+3  A: 

You can simple list the class names:

.foo.bar.bar

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

Gumbo
How does that relate to the use case he listed? E.g., wanting to query an instance/list via `hasClass`, `is`, etc.? (It would apply if he were trying to *get* a list...) Or can you pass that into `hasClass` or something?
T.J. Crowder
@T.J. Crowder: `.is(".foo.bar.bar")`
mcrumley
+1  A: 

You could simply do:

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

... or use a selector

$(".test.othertest");

marcgg
Ok, so maybe I have to exemplify: function checkFilter() { $('.post').each(function(){ if ($(this).hasClass('photography')
emilolsson
@emilolsson please edit your question with these info, it's not really readable in the comments ^^
marcgg
+2  A: 

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.
John Hartsock
Thanks for clearing this out! Works now.
emilolsson
+2  A: 

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?

kevingessner
Yes, you're right.. I used is() in the wrong way!! Thanks for all the help...
emilolsson