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.

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

  1. 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
    }

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

  2. 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
    }

  3. Pingback: Code.AdamJZeffer.com - How to check if a class exists in an element

  4. 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/

Comments are closed.

Scroll to Top