Where is the hasClass method?

Monday, June 25, 2007

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)
};

You can download the source code and see an example here for this hasClass method.

Posted in jQuery with 2 comments

Comments

Hey Brandon, excellent entry! You’re right, this (.)is an oft-requested method on the list (sorry for the ridiculously bad play on words). Great to see that you’ve often an easy-to-implement option for those who are looking for hasClass!

By Karl Swedberg on Monday, June 25, 2007 at 06:10 PM

Cheers, I wasn’t aware of how .is() works - very useful.

By Tamlyn Rhodes on Thursday, July 26, 2007 at 09:18 AM

New Comment