Add a class to multiple Elements using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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'); }

add class multiple elements

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 use 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 classList.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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.