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
Removing one class from an element requires a bit of manipulation of the className
property.
var toRemove = "bar",
el = document.getElementById("link1");
el.className = el.className.replace(new RegExp("\\b" + toRemove + "\\b", "g"), "").trim();
Removing multiple class names would require a loop. The remaining examples will use a function to isolate the work
function removeClass(el, name) {
name = name.split(/\s+/);
var index = name.length,
classes = el.className;
while (index--) {
classes = classes.replace(new RegExp("\\b" + name[index] + "\\b", "g"), "").trim();
}
el.className = classes;
}
var el = document.getElementById("link1");
removeClass(el, "bar baz");
Multiple elements with multiple class names to remove would require two loops
function removeClass(els, name) {
name = name.split(/\s+/);
var regex, len,
index = name.length;
while (index--) {
regex = new RegExp("\\b" + name[index] + "\\b", "g");
len = els.length;
while (len--) {
els[len].className = els[len].className.replace(regex, "").trim();
}
}
}
var els = document.getElementsByTagName("a");
removeClass(els, "bar baz");
A single class name may be removed as a string. To remove multiple class names, use ES6's spread operator:
document.querySelector("#link1").classList.remove("foo");
document.querySelector("#link2").classList.remove(...['foo', 'bar']);
For multiple elements, you'll need to remove the class names inside of a loop
document.querySelectorAll(".foo").forEach(el => {
el.classList.remove(...['bar', 'baz']);
});