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

by Yang Yang on April 16, 2009

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.

Subscribe to Kavoir: blog feed

You should also read:

Tom February 13, 2010 at 9:56 am

Excellent thanks, just what I needed.

Khaleel May 6, 2010 at 11:58 am

Thanks this works…

ivan June 28, 2010 at 4:14 pm

Thanks! This helps me in my coding.

Suppy July 21, 2010 at 8:43 pm

Thanks :) I got it!

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

Test February 8, 2011 at 10:58 pm


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

Max February 9, 2011 at 5:56 am

Thank you very much, helps me a lot.

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/

Torey Scheer May 27, 2012 at 7:25 am

Hey, thanks, that worked. I think is only works if something has 1 class, which I have 2.

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

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

Thanks. It works great :-)

Miles January 26, 2012 at 4:57 am

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

Parhum March 10, 2012 at 3:05 pm

Thanks, it’s useful :)

Shaharia Azam March 27, 2012 at 5:39 am

Hey guyz,
You don’t need to use is() here. There is a special jQuery function (hasClass) to check the existing class of a DOM element. Check my following.

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

for more details: http://api.jquery.com/hasClass/

Zubaer September 28, 2012 at 1:38 pm

Thanks.. It saw very helpful to me

Rafael March 20, 2013 at 2:03 am

Thank you very much!

Comments on this entry are closed.

{ 1 trackback }

Previous post:

Next post: