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.
A simple method to add a class to an element is to append it to the end of the className
property. This will not prevent duplicate class names, and spaces must be included between class names.
document.getElementById("link1").className += " foo";
document.getElementById("link2").className += " foo bar";
For multiple elements, you'll need to add the class names inside of a loop
var els = document.getElementsByClassName("foo"),
indx = els.length;
while (indx--) {
els[indx].className += " bar baz";
}
A single class name may be added as a string. To add multiple class names, use ES6's spread operator:
document.querySelector("#link1").classList.add("foo");
document.querySelector("#link2").classList.add(...['foo', 'bar']);
For multiple elements, you'll need to add the class names inside of a loop
document.querySelectorAll(".foo").forEach(el => {
el.classList.add(...['bar', 'baz']);
});