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 comments

  1. Tom

    Excellent thanks, just what I needed.

  2. Khaleel

    Thanks this works…

  3. ivan

    Thanks! This helps me in my coding.

  4. Suppy

    Thanks :) I got it!

  5. Jared Heinrichs

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

  6. Test

    [code]
    $(this)
    [/code]

  7. Damien van Holten

    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
    }

  8. Max

    Thank you very much, helps me a lot.

  9. Joshua Oiknine

    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

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

  10. Christian Esperar

    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
    }

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

  12. Miles

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

  13. Parhum

    Thanks, it’s useful :)

  14. Shaharia Azam

    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/

  15. Zubaer

    Thanks.. It saw very helpful to me

  16. Rafael

    Thank you very much!