JAVASCRIPT

Dynamically Create and Append Multiple Elements

Learn how to programmatically create new HTML elements like 'div's and 'p's using JavaScript's DOM API and efficiently append them to an existing container.

function createAndAppendElements(containerId, items) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error('Container not found:', containerId);
    return;
  }

  items.forEach(itemText => {
    const newItem = document.createElement('div');
    newItem.classList.add('item-card');
    newItem.textContent = itemText;
    newItem.setAttribute('data-id', itemText.replace(/\s+/g, '-').toLowerCase());
    container.appendChild(newItem);
  });
}

// Example usage:
// <div id="myContainer"></div>
// createAndAppendElements('myContainer', ['Item One', 'Item Two', 'Item Three']);
How it works: This function takes a container ID and an array of strings. For each string, it creates a new `div` element, adds a CSS class, sets its text content, adds a custom `data-id` attribute, and then appends it as a child to the specified container. This is a fundamental way to build UI dynamically without relying on `innerHTML` for better security and performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs