Where is the hasClass method?
A common question on the jQuery mailing list is: “Where is the hasClass method?”. jQuery has a very flexible method named is
. This method takes an expression to test against. For example you could see if a particular element is a form element.
$('#myElement').is('form');
This will return true
or false
if the element is a form or not. This method is pretty flexible and makes sense but it can be a little hard to find. We can check to see if an element is of a particular class (or has a class name) by simply using a class selector/expression.
$('#myElement').is('.myClass');
Again, this will return true
or false
if the element has the class name ‘myClass’ or not.
Even better in the upcoming jQuery 1.1.3, the is
method can take a comma separated list to test against.
$('#myElement').is('.myClass, .myOtherClass');
This will return true
if the element has either ‘myClass’ or ‘myOtherClass’, otherwise it returns false
.
Even though the is
method is flexible and can check for a class it can be helpful to have an actual hasClass
method. Actually a hasClass
method is currently on the table for inclusion in jQuery 1.2. Here is a hasClass
method that you can include in your code now.
jQuery.fn.hasClass = function(c) {
return this.is('.'+c)
};