Categories
JavaScript Tips & Tutorials jQuery Tips & FAQ

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

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.

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

18 replies on “jQuery: How to check if an element has a particular class”

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
}

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

Comments are closed.