JAVASCRIPT

Efficiently Create and Append Multiple DOM Elements

Learn how to dynamically create and append multiple new DOM elements to the page efficiently using DocumentFragment to minimize reflows and repaints.

function createAndAppendMultipleElements(parentId, items) {
  const parentElement = document.getElementById(parentId);
  if (!parentElement) {
    console.error(`Parent element with ID '${parentId}' not found.`);
    return;
  }

  const fragment = document.createDocumentFragment();

  items.forEach(itemText => {
    const li = document.createElement('li');
    li.textContent = itemText;
    li.classList.add('list-item'); // Add a class for styling
    fragment.appendChild(li);
  });

  parentElement.appendChild(fragment);
}

// Example Usage:
// <div id="myListContainer"></div>
// createAndAppendMultipleElements('myListContainer', ['Item 1', 'Item 2', 'Item 3']);
How it works: This snippet demonstrates how to efficiently create and append multiple new DOM elements. Instead of appending each element individually to the live DOM, which can cause performance issues due to repeated reflows and repaints, it uses a DocumentFragment. Elements are first appended to this fragment, and then the fragment itself is appended to the parent element in a single operation, leading to better performance and a smoother user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs