Change a style of all Elements with specific Class using JS


Borislav Hadzhiev

Sun Jan 09 20222 min read


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.

<!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.

const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { = 'purple'; = '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.

const boxes = Array.from( document.getElementsByClassName('box') ); boxes.forEach(box => { = 'purple'; = '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.