JAVASCRIPT
Update Text Content of Multiple Elements by Class
Efficiently update the text content of all elements sharing a common CSS class on your webpage using JavaScript's querySelectorAll and forEach methods.
function updateTextByClass(className, newText) {
const elements = document.querySelectorAll(`.${className}`);
if (elements.length === 0) {
console.warn(`No elements found with class '${className}'.`);
return;
}
elements.forEach(element => {
element.textContent = newText;
});
}
// Example Usage:
// Assume the following elements exist in your HTML:
// <p class="status-message">Loading...</p>
// <span class="status-message">Pending</span>
// <div class="status-message">Processing...</div>
updateTextByClass('status-message', 'Operation Complete!');
How it works: This function selects all elements that share a specific CSS class using document.querySelectorAll(), which returns a NodeList. It then iterates over this NodeList using forEach() and updates the textContent property of each matching element to the new specified text. This is highly useful for mass updates of UI labels or status messages across multiple similar components.