Change a style of all Elements with specific Class using JS

avatar

Borislav Hadzhiev

Sun Jan 09 20222 min read

banner

Photo by Irene Dávila

Change the style of all Elements with specific Class #

To change the styles of all elements with a specific class:

  1. Use the querySelectorAll() method to get a collection of the elements with the specific class.
  2. Use the forEach() method to iterate over the collection.
  3. On each iteration, use the style object to change the element's styles.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .box { background-color: salmon; color: white; width: 150px; height: 150px; margin: 10px; } </style> </head> <body> <div class="box">Box content 1</div> <div class="box">Box content 2</div> <div class="box">Box content 3</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { box.style.backgroundColor = 'purple'; box.style.width = '300px'; });

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

The querySelectorAll method returns a NodeList containing the elements that match the selector.

The function we passed to the forEach method gets called with each element in the NodeList.

On each iteration, we set properties on the element's style object to update its styles.

Note that multi-word properties like background color are camel-cased when accessed on the style object.

You could also use the document.getElementsByClassName method to select the elements with the specific class, however the method returns an HTMLCollection.

Make sure to convert the HTMLCollection to an array before calling the forEach method on it.

index.js
const boxes = Array.from( document.getElementsByClassName('box') ); boxes.forEach(box => { box.style.backgroundColor = 'purple'; box.style.width = '300px'; });

The code snippet above achieves the same result as the previous snippet.

We used the Array.from method to convert the HTMLCollection to an array before calling the forEach method.

If I open my browser, I can see that the inline styles have been successfully applied to all elements with the class of box.

styles applied to elements with class

Use the search field on my Home Page to filter through my more than 1,000 articles.