Add a class to multiple Elements using JavaScript

avatar

Borislav Hadzhiev

Thu Dec 30 20212 min read

banner

Photo by Anonymous

Add a class to multiple Elements using JavaScript #

To add a class to multiple elements:

  1. Select the elements using the document.querySelectorAll() method.
  2. Use a for...of loop to iterate over the collection of elements.
  3. Use the classList.add method to add a class to each 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-yellow { background-color: yellow; } </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) { box.classList.add('bg-yellow'); }

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

We used the for...of loop to iterate over the collection of elements.

On each iteration, we used the classList.add method to add a class to the element.

If the class is already present on the element, it won't get added twice.

You can pass as many classes to the add() method as necessary.

index.js
const boxes = document.querySelectorAll('.box'); for (const box of boxes) { box.classList.add( 'bg-yellow', 'second-class', 'third-class' ); }

Similarly, if you need to remove one or more classes, you can use the remove() method.

index.js
const boxes = document.querySelectorAll('.box'); for (const box of boxes) { box.classList.add( 'bg-yellow', 'second-class', 'third-class' ); box.classList.remove( 'second-class', 'third-class' ); }
The querySelectorAll method takes one or more selectors, so we are able to select elements with multiple different classes, ids, etc.

Here is an example that uses the method to get a collection of elements with 3 different classes.

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

And here is the related JavaScript code.

index.js
const boxes = document.querySelectorAll('.box1, .box2, .box3'); for (const box of boxes) { box.classList.add('bg-yellow', 'second-class', 'third-class'); box.classList.remove('second-class', 'third-class'); }

We passed 3 different selectors to the querySelectorAll method by separating them with commas.

You could pass an id to a method by prefixing the id value with a #, e.g. #my-id.

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