DOM Manipulating a list of CSS classes Adding a class


Example

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.

W3C DOM4

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";
}
W3C DOM4

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']);
});