Mitchel Sellers Mitchel Sellers - 1 year ago 40
CSS Question

Determine if an element has a CSS class with jQuery

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.

Answer Source

Use the hasClass method:




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')