JAVASCRIPT
Update Text Content of Multiple Elements
Efficiently update the text content of all HTML elements that share a common CSS class using document.querySelectorAll and a simple loop.
function updateElementsTextByClass(className, newText) {
const elements = document.querySelectorAll(`.${className}`);
elements.forEach(element => {
element.textContent = newText;
});
console.log(`${elements.length} elements with class '${className}' updated.`);
}
// Example Usage:
// Assume HTML: <p class="info">Old Text 1</p><span class="info">Old Text 2</span>
// updateElementsTextByClass('info', 'New updated information!');
How it works: This function selects all elements that have a specific CSS class using `document.querySelectorAll`. It then iterates through the resulting NodeList and updates the `textContent` property of each element to the provided `newText`. This is a straightforward and efficient way to perform bulk text updates across multiple DOM elements without affecting their HTML structure.