Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 209
anonymous Avatar asked Jan 01 '10 12:01

anonymous


People also ask

Can an element have multiple CSS classes?

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.

How do you delete multiple classes in an element?

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') .

How do you add multiple classes to an element in CSS?

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.

Can you add multiple classes to an element JavaScript?

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') .


2 Answers

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.

like image 87
ericsoco Avatar answered Sep 18 '22 16:09

ericsoco


Try doing this...

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

Got this here...

like image 21
Ryan Avatar answered Sep 16 '22 16:09

Ryan