How to Change the Style of All Elements with a Specific Class in JavaScript
A common task in DOM manipulation is to apply a style change to a group of elements that share the same class. For example, you might want to highlight all "warning" elements or change the background color of every item in a list. To do this, you need to select all the elements and then loop through them to apply the new style to each one.
This guide will teach you the modern, standard method for this task using document.querySelectorAll() and the .forEach() method. You will also learn about the older getElementsByClassName method and the key differences between them.
Core Task: Select All, Then Iterate
You cannot change the style of multiple elements at once. There is no command like document.getAll('.my-class').style.color = 'red'. This will not work because methods that select multiple elements return a collection (which is like an array), not a single element.
The correct process is always:
- Select all the elements with the specific class to get a collection.
- Iterate (loop) through that collection.
- Inside the loop, apply the style change to each individual element.
The Modern Method (Recommended): querySelectorAll with forEach
The document.querySelectorAll() method is the modern and most flexible way to select multiple elements. It uses CSS selectors, just like you would in a stylesheet, and returns a NodeList. A NodeList has a built-in .forEach() method, making it very easy to iterate over.
Consider the following HTML code:
<!DOCTYPE html>
<html>
<body>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div id="other">Not a box</div>
<div class="box">Box 3</div>
<script src="index.js"></script>
</body>
</html>
And this is the JavaScript solution: when this code runs, all three divs with the class box will have their background color changed to blue.
// 1. Select all elements with the class 'box'. The '.' is crucial.
const boxes = document.querySelectorAll('.box');
// 2. Iterate over the NodeList using the forEach method.
boxes.forEach(box => {
// 3. Apply styles to each element.
box.style.backgroundColor = 'blue';
box.style.color = 'white';
});
The Older Method: getElementsByClassName with a for...of Loop
An older method is document.getElementsByClassName(). It achieves a similar result but returns an HTMLCollection instead of a NodeList. An HTMLCollection does not have a .forEach() method, so you must use a different kind of loop, like a for...of loop.
// 1. Select all elements with the class 'box'. No '.' is needed here.
const boxes = document.getElementsByClassName('box');
// 2. Iterate over the HTMLCollection using a for...of loop.
for (const box of boxes) {
// 3. Apply styles to each element.
box.style.backgroundColor = 'green';
box.style.color = 'white';
}
Comparison of the two solutions (NodeList vs. HTMLCollection)
The difference between these two methods is subtle but important.
querySelectorAllreturns a staticNodeList. "Static" means the list is a snapshot of the DOM at the time you made the query. It will not change if you add or remove elements later. It has a convenient.forEach()method.getElementsByClassNamereturns a liveHTMLCollection. "Live" means if you add a new element with that class to the DOM, the collection will automatically update to include it. It does not have a.forEach()method, so you must use afor...ofloop or convert it to an array first (Array.from(boxes)).
Recommendation: For most use cases, querySelectorAll is the preferred and more intuitive method.
A Note on CSS vs. Inline Styles
The .style property in JavaScript sets inline styles on an element. This is the equivalent of writing <div style="background-color: blue;">. While this works perfectly, for more complex or reusable styling, the best practice is to add or toggle a CSS class.
.highlight {
background-color: blue;
color: white;
border: 2px solid navy;
}
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => {
box.classList.add('highlight');
});
This approach is cleaner because it separates your styling (CSS) from your application logic (JavaScript).
Conclusion
To change the style of all elements with a specific class, you must select them all and then loop through the resulting collection.
The key takeaways are:
- The
document.querySelectorAll('.my-class')method is the modern and recommended way to select the elements. - The result of
querySelectorAllis aNodeList, which you can easily iterate over with the.forEach()method. - Inside the loop, you can modify the
.styleproperty of each individual element to change its appearance. - For more maintainable code, prefer toggling a CSS class over setting multiple inline styles.