views:

20015

answers:

3

I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.

I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.

+43  A: 

Use the hasClass method:

jQueryCollection.hasClass(className);

or

$(selector).hasClass(className);

The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).

eyelidlessness
Exactly. Documentation here: http://docs.jquery.com/Traversing/hasClass
Nathan Long
Wow, all that looking and I still missed it
Mitchel Sellers
yeah their documentation isn't so great in my opinion.
Triptych
I disagree. The documentation's organized under categories, but you can easily see all the methods alphabetically as well. Everything comes with an example, and the comments section usually clears up anything that's left out. jQuery has a LOT of excellent functions and utilities and it takes some learning to discover them all.-EDIT- That makes sense, it's definitely come a long way.
Trafalmadorian
@Trafalmadorian, I've removed my original comment because the situation has changed. Originally you had posted everything before -EDIT-, and I replied that my comment about the documentation quality was no longer relevant but referred to their previous (MediaWiki) system. You then deleted your previous comment and reposed with the -EDIT-. I hope that this cleanup is a little clearer and less misleading to future readers.
eyelidlessness
+7  A: 

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}
Javier
Your use of if statements without parentheses is a syntax error.
eyelidlessness
tks, fixed.
Javier
careful with .is() - "The is() method in jQuery will return true if ANY of the elements in the current collection match ANY of the elements in the is-based collection" - http://www.bennadel.com/blog/1725-jQuery-s-is-Method-Checks-For-Any-Matching-Elements.htm
zack
A: 

As for the negation, if you want to know if an element hasn't a class you can simply do as Mark said.

if (!currentPage.parent().hasClass('home')) { do what you want }
VinnyG