How do I test whether an element has a particular class?

jQuery

How do I test whether an element has a particular class?

hasClass (added in version 1.2) handles this common use case:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
                          
$("div").click(function() {
if ( $( this ).hasClass("protected") ) {
$( this )
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: 0 });
}
});

You can also use the is() method along with an appropriate selector for more advanced matching:

1
2
3
4
5
                          
if ( $("#myDiv").is(".pretty.awesome") ) {
$("#myDiv").show();
}

Note that this method allows you to test for other things as well. For example, you can test whether an element is hidden (by using the custom :hidden selector):

1
2
3
4
5
                          
if ( $("#myDiv").is(":hidden") ) {
$("#myDiv").show();
}