Modern browsers provide a classList
object to ease manipulation of the element's class attribute. Older browsers require direct manipulation of the element's className
property.
* Note class names are not stored in the element's property in any particular order
Testing if an element contains a class requires a bit of manipulation of the className
property. This example is using an array method to test for the class.
function hasClass(el, name) {
var classes = (el && el.className || "").split(/\s+/);
return classes.indexOf(name) > -1;
}
var el = document.getElementById("link1");
console.log(hasClass(el, "foo"));
Testing for multiple class names would require a loop.
function hasClass(el, name) {
name = name.split(/[\s.]+/);
var hasClass = true,
classes = (el && el.className || "").split(/\s+/),
index = name.length;
while (index--) {
hasClass = hasClass && classes.indexOf(name[index]) > -1;
}
return hasClass;
}
var el = document.getElementById("link1");
console.log(hasClass(el, "foo"));
Instead of using .indexOf()
, you may also consider using a regular expression.
function hasClass(el, name) {
return new RegExp("\\b" + name+ "\\b").test(el.className);
}
var el = document.getElementById("link1");
console.log(hasClass(el, "foo"));
Testing for a single class name is done as follows:
var hasClass = document.querySelector("#link1").classList.contains("foo");
For multiple class names, it is easier to use matches
. Note the use of the class selector; The selector can be any valid string selector (id, attribute, pseudo-classes, etc).
var hasClass = document.querySelector("#link1").matches('.foo.bar');
var hasClass = document.querySelector("#link2").matches('a.bar[href]');