Borislav Hadzhiev
Sun Jan 09 2022·2 min read
Photo by Irene Dávila
To change the styles of all elements with a specific class:
querySelectorAll()
method to get a collection of the elements with
the specific class.forEach()
method to iterate over the collection.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 => { box.style.backgroundColor = 'purple'; box.style.width = '300px'; });
We used the
document.querySelectorAll
method to select all DOM elements with a class of box
.
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
.
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 => { 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
.