JavaScript CSS how to add and remove multiple CSS classes to an element

How can assign multiple css classes to an html element through javascript without using any libraries?


Solution 1:

Here's a simpler method to add multiple classes via classList (supported by all modern browsers, as noted in other answers here):

div.classList.add('foo', 'bar'); // add multiple classes

From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples

If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add() via this one-liner:

let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);

Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.

Solution 2:

Try doing this...

document.getElementById("MyElement").className += " MyClass";

Got this here...

Solution 3:

This works:

myElement.className = 'foo bar baz';

Solution 4:

There are at least a few different ways:

var buttonTop = document.getElementById("buttonTop");

buttonTop.className = "myElement myButton myStyle";

buttonTop.className = "myElement";

buttonTop.className += " myButton myStyle";

buttonTop.classList.add("myElement");

buttonTop.classList.add("myButton", "myStyle");

buttonTop.setAttribute("class", "myElement");

buttonTop.setAttribute("class", buttonTop.getAttribute("class") + " myButton myStyle");

buttonTop.classList.remove("myElement", "myButton", "myStyle");