JAVASCRIPT

Update Text Content of Multiple Elements Dynamically

Learn how to select and update the text content of multiple HTML elements (e.g., list items, paragraphs) on the page using JavaScript effectively.

function updateMultipleElementsText(selector, newTextArray) {
  const elements = document.querySelectorAll(selector);

  if (elements.length === 0) {
    console.warn(`No elements found matching selector '${selector}'.`);
    return;
  }

  elements.forEach((element, index) => {
    if (newTextArray && newTextArray[index] !== undefined) {
      element.textContent = newTextArray[index];
      console.log(`Updated element ${index} with text: '${newTextArray[index]}'.`);
    } else {
      // Fallback or skip if not enough newTextArray items
      console.warn(`No new text provided for element ${index} matching selector '${selector}'.`);
    }
  });
}

// Example Usage:
// HTML structure:
// <ul id="myList">
//   <li>Item 1</li>
//   <li>Item 2</li>
//   <li>Item 3</li>
// </ul>
updateMultipleElementsText('#myList li', ['Updated Item A', 'Updated Item B', 'Updated Item C']);

// If you want to update all with the same text:
// updateMultipleElementsText('.status-message', ['New Status!']);
How it works: This snippet illustrates how to efficiently update the text content of multiple elements that match a specific CSS selector. The `updateMultipleElementsText` function takes a selector and an array of new text strings. It uses `document.querySelectorAll()` to gather all matching elements. Then, it iterates through these elements using `forEach` and assigns new text from the `newTextArray` to each element's `textContent` property based on its index. This is useful for dynamically populating lists, tables, or updating status indicators across a page.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs