JAVASCRIPT
Update Multiple DOM Elements by Class Name
Learn to efficiently select and modify text content, styles, or attributes for multiple DOM elements that share a common CSS class using JavaScript.
function updateElementsByClass(className, newText, newColor) {
const elements = document.getElementsByClassName(className); // Returns an HTMLCollection
// Alternatively, using querySelectorAll (returns a NodeList):
// const elements = document.querySelectorAll(`.${className}`);
if (elements.length === 0) {
console.warn(`No elements found with class '${className}'.`);
return;
}
// Iterate and update each element
Array.from(elements).forEach(element => { // Convert HTMLCollection to Array for forEach
element.textContent = newText;
element.style.color = newColor;
element.setAttribute('data-status', 'updated'); // Set an attribute
});
}
// Example HTML:
// <p class="status-message">Old message 1</p>
// <div class="status-message">Old message 2</div>
// Example Usage:
// updateElementsByClass('status-message', 'New Status: Active!', 'green');
How it works: This snippet shows how to select and modify multiple DOM elements that share a specific CSS class. It uses document.getElementsByClassName() to retrieve a live HTMLCollection of matching elements. The code then iterates over this collection (converted to an array for forEach compatibility) to update each element's textContent, inline style.color, and a custom data-status attribute. This is a common pattern for bulk updates based on a shared characteristic.