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.
Excellent thanks, just what I needed.
Thanks this works…
Thanks! This helps me in my coding.
Thanks 🙂 I got it!
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 🙂
[code]
$(this)
[/code]
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
}
Thank you very much, helps me a lot.
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/
Hey, thanks, that worked. I think is only works if something has 1 class, which I have 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
}
Pingback: Code.AdamJZeffer.com - How to check if a class exists in an element
Thanks. It works great 🙂
if ($(this).is(‘what I needed’)
Thanks, it’s useful 🙂
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/
Thanks.. It saw very helpful to me
Thank you very much!