Object.hasClass()
Update: For compatibility, Object.hasClass(className) is being changed to simply hasClass(node, className).
Inspired by the dojo toolkit, this function checks to see if a given class is assigned to a node. Simply run it like this:
var my_node = document.getElementsById("mydiv");
if( hasClass(my_node, "myclass") ) {
// ...do something
}
Enough talk; here’s the code:
function hasClass( /*HTMLElement:*/node, /*String:*/value ) {
return (" "+node.className+" ").match(" "+value+" ") ? true : false;
};
It works like this. Since the class attribute has multiple values separated by spaces, you simply add a space to the beginning and one to the end. Then add spaces to the beginning of the value. Then if the value string is contained within the class string, the element has the class.
Enjoy!
« the ultimate getElementsBy*: Object.getElementsWhere()