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.

  1. $('#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.

  1. $('#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.

  1. $('#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.

  1. jQuery.fn.hasClass = function(c) {
  2.     return this.is('.'+c)
  3. };

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

2 Responses to “Where is the hasClass method?”

  1. Karl Swedberg Says:

    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!

  2. Tamlyn Rhodes Says:

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

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>