JAVASCRIPT
Update Text and Attributes for Multiple Elements by Class
Learn to efficiently select and update the text content and attributes for multiple HTML elements sharing a common CSS class using JavaScript's `querySelectorAll` method.
function updateElementsByClass(className, newText, newAttributes = {}) {
const elements = document.querySelectorAll(`.${className}`);
if (elements.length === 0) {
console.warn(`No elements found with class '${className}'.`);
return;
}
elements.forEach(element => {
if (newText !== undefined) {
element.textContent = newText;
}
for (const attr in newAttributes) {
if (newAttributes.hasOwnProperty(attr)) {
element.setAttribute(attr, newAttributes[attr]);
}
}
console.log(`Element updated: ID=${element.id || 'N/A'}, Class=${element.className}`);
});
}
// Example Usage:
// Assuming you have HTML like:
// <p class="update-me" id="item1">Original text 1</p>
// <div class="update-me" data-value="old">Original text 2</div>
// updateElementsByClass('update-me', 'New updated text!', { 'data-status': 'processed', style: 'color: blue;' });
How it works: This JavaScript snippet shows how to locate and modify multiple HTML elements that share a specific CSS class. It uses `document.querySelectorAll()` to gather all matching elements and then iterates over them using `forEach`. For each element, it updates its `textContent` and applies any provided new attributes using `setAttribute()`, offering a powerful way to make bulk DOM changes based on dynamic conditions.