Last updated: Mar 5, 2024
Reading time·2 min
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.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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
NodeList.forEach()
method gets called with each element in the NodeList
.
style
object to update its styles.const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { box.style.backgroundColor = 'purple'; box.style.width = '300px'; });
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.
const boxes = Array.from( document.getElementsByClassName('box') ); boxes.forEach(box => { box.style.backgroundColor = 'purple'; box.style.width = '300px'; });
The code snippet achieves the same result by using the
getElementsByClassName()
method.
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
.
Alternatively, you can iterate over the HTMLCollection directly without
converting it to an array by using a for...of
loop.
const boxes = document.getElementsByClassName('box'); for (const box of boxes) { box.style.backgroundColor = 'purple'; box.style.width = '300px'; }
The for...of statement is
used to loop over iterable objects like arrays, strings, Map
, Set
and
NodeList
objects and generators
.
You can learn more about the related topics by checking out the following tutorials: