Add multiple classes to an Element using JavaScript

avatar

Borislav Hadzhiev

Thu Dec 30 20212 min read

banner

Photo by Anonymous

Add multiple classes to an Element using 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'). The add() method takes one or more classes and adds them to the element.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-blue { background-color: blue; } .text-white { color: white; } </style> </head> <body> <div id="box">Box 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // โœ… Add multiple classes box.classList.add('bg-blue', 'text-white'); // โœ… Remove multiple classes box.classList.remove('first-class', 'second-class');

We selected the element using the document.getElementById() method.

Then we used the classList.add method to add multiple classes to the element.

If a class is already present on the element, it will be omitted. The add() method only adds classes that are not already contained in the element's class list.

You can pass one or more classes to the add() method, but if you pass an empty string argument or an argument that contains a space, the method throws an error.

If you need to remove one or more classes, use the remove() method, which takes one or more class names as parameters and removes them from the element.

The classList.add() method has to be invoked on a DOM element, so if you have a collection of elements, you have to iterate over it and call the method on each.

Here is the HTML for the next example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-blue { background-color: blue; } .text-white { color: white; } </style> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const boxes = document.querySelectorAll('.box'); for (const box of boxes) { // โœ… Add multiple classes box.classList.add('bg-blue', 'text-white'); // โœ… Remove multiple classes box.classList.remove('first-class', 'second-class'); }

We used the document.querySelectorAll method to select all of the elements in the DOM with a class of box.

We used the for...of loop to iterate over the collection and added multiple classes to each element.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee