jQuery: How to check if an element has a particular class

by Yang Yang on April 16, 2009

Share This Article:
Subscribe to Kavoir: blog feed

To know whether a class exists on an element with jQuery, you need a simple test method: is().

For example, to test if an element #elm has the class ‘first’:

if ($(#elm).is('.first')) {
//#elm has the class
} else {
//#elm doesn't have the class
}

jQuery is() is the function that checks if any of the returned DOM objects from the selector satisfies the criteria set in the argument.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 12 comments… read them below or add one }

Tom February 13, 2010 at 9:56 am

Excellent thanks, just what I needed.

Reply

Khaleel May 6, 2010 at 11:58 am

Thanks this works…

Reply

ivan June 28, 2010 at 4:14 pm

Thanks! This helps me in my coding.

Reply

Suppy July 21, 2010 at 8:43 pm

Thanks :) I got it!

Reply

Jared Heinrichs November 1, 2010 at 12:03 am

How would you find out the class using “this”. For example if an achor tag is clicked find out if it has a tag = “bigger”? Any help would be appreciated :)

Reply

Test February 8, 2011 at 10:58 pm

[code]
$(this)
[/code]

Reply

Damien van Holten February 8, 2011 at 11:00 pm

Your code is actually incorrect. Selectors need to be in between apostrophes (‘). The follow code is correct:

if ($(‘#elm’).is(‘.first’)) {
//#elm has the class
} else {
//#elm doesn’t have the class
}

@Jared Heinrichs

Do you mean something like this?

if ($(this).is(‘.bigger’)) {
//#elm has the class
} else {
//#elm doesn’t have the class
}

Reply

Max February 9, 2011 at 5:56 am

Thank you very much, helps me a lot.

Reply

Joshua Oiknine March 25, 2011 at 12:11 pm

There is a method .hasClass() since version 1.2 that is clearer to use. hasClass will probably preform better than .is as it does not need to attempt to match anything else to get its results. http://api.jquery.com/hasClass/

Reply

Christian Esperar August 27, 2011 at 7:12 pm

Thanks! You’re a great help! May I correct? It must have a ” in the #element

if ($(“#element”).is(‘.class’)) {
//#element has the class
} else {
//#element doesn’t have the class
}

Reply

Jerome Dennis D December 11, 2011 at 1:17 am

Thanks. It works great :-)

Reply

Miles January 26, 2012 at 4:57 am

if ($(this).is(‘what I needed’)

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: