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.
You should also read:
- jQuery: How to test or check whether an element exists
- jQuery: Selecting elements with uncommon / special characters in ID or class name
- jQuery: Protecting or hiding variables / functions in a specific local scope
- PHP: File Upload Script (HTML Form + PHP Handler Class)
- MySQL: Insert if doesn’t exist otherwise update the existing row


Facebook
Twitter
Google Plus
{ 12 comments… read them below or add one }
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/
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
}
Thanks. It works great :-)
if ($(this).is(‘what I needed’)
{ 1 trackback }