What is the best way to check if the item has a class?

advertisements

The problem

If the element has multiple classes then it will not match with the regular property value checking, so I'm looking for the best way to check if the object has a particular class in the element's className property.

Example

// element's classname is 'hello world helloworld'
var element = document.getElementById('element');

// this obviously fails
if(element.className == 'hello'){ ... }

// this is not good if the className is just 'helloworld' because it will match
if(element.className.indexOf('hello') != -1){ ... }

So what would be the best way to do this?

just pure javascript please


function hasClass( elem, klass ) {
     return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}