Determine if an element has a CSS class with jQuery
from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
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 }
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).
Note: If you pass a className
argument that contains whitespace, it will be matched literally against the collection's elements' className
string. So if, for instance, you have an element,
<span class="foo bar" />
then this will return true
:
$('span').hasClass('foo bar')
and these will return false
:
$('span').hasClass('bar foo')
$('span').hasClass('foo bar')