Determine if an element has a CSS class with jQuery

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.


Solution 1:

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

Solution 2:

from the FAQ

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


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

Solution 3:

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 }

Solution 4:

Without jQuery:

var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;


function hasClass(e,c){
    return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);
/*example of usage*/
var has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');

This is WAY faster than jQuery!

Related:  Understanding Javascript immutable variable

Solution 5:

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:


Solution 6:

Check the official jQuery FAQ page :

How do I test whether an element has perticular class or not