JAVASCRIPT
Update Multiple Text Contents of Selected Elements
Learn to efficiently update the text content of multiple elements in the DOM using querySelectorAll and textContent, perfect for lists or repeated elements.
function updateListItemsText(selector, newTextArray) {
const elements = document.querySelectorAll(selector);
if (elements.length === 0) {
console.warn(`No elements found with selector: ${selector}`);
return;
}
elements.forEach((element, index) => {
if (newTextArray[index] !== undefined) {
element.textContent = newTextArray[index];
}
});
}
// Example Usage:
// HTML structure:
// <ul id="myDynamicList">
// <li>Old Text 1</li>
// <li>Old Text 2</li>
// <li>Old Text 3</li>
// </ul>
const updatedTexts = ['New Text A', 'New Text B', 'New Text C', 'Extra Text D (will not be used if elements are fewer)'];
updateListItemsText('#myDynamicList li', updatedTexts);
// After execution, the list items will have 'New Text A', 'New Text B', 'New Text C'.
How it works: This snippet demonstrates how to update the text content of multiple DOM elements based on a CSS selector. It uses `document.querySelectorAll()` to get a NodeList of all matching elements and then iterates over them using `forEach`. For each element, it updates its `textContent` property with a corresponding value from the `newTextArray`. This is a clean and efficient way to refresh dynamic lists or blocks of text without rebuilding the entire HTML structure.