How can I check in JavaScript if a DOM element contains a class?
I tried the following code, but for some reason it doesn\'t work...
if (document.get
The property you need is className
, not class
. Also, an element can have many classes, so if you want to test if it has a particular class you need to do something like the following:
function hasClass(el, clss) {
return el.className && new RegExp("(^|\\s)" +
clss + "(\\s|$)").test(el.className);
}
var element = document.getElementById('element');
if ( hasClass(element, "class_one") ) {
// Do stuff here
}
UPDATE
Modern browsers (pretty much everything major except IE <= 9) support a classList
property, as mentioned in @Dropped.on.Caprica's answer. It therefore makes sense to use this where available. Here's some example code that detects whether classList
is supported by the browser and falls back to the regex-based code otherwise:
var hasClass = (typeof document.documentElement.classList == "undefined") ?
function(el, clss) {
return el.className && new RegExp("(^|\\s)" +
clss + "(\\s|$)").test(el.className);
} :
function(el, clss) {
return el.classList.contains(clss);
};