How can assign multiple css classes to an html element through javascript without using any libraries?
An element is usually only assigned one class. The corresponding CSS for that particular class defines the appearance properties for that class. However, we can also assign multiple classes to the same element in CSS.
To remove multiple classes from an element, select the element and pass multiple class names to the classList. remove() method, e.g. box. classList. remove('bg-blue', 'text-white') .
To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element. Naming rules: Must begin with a letter A-Z or a-z.
To add multiple classes to an element, select the element and pass multiple classes to the classList. add() method, e.g. box. classList. add('bg-blue', 'text-white') .
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.
Try doing this...
document.getElementById("MyElement").className += " MyClass";
Got this here...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With