JAVASCRIPT

Dynamically Create and Append Multiple DOM Elements Efficiently

Learn how to efficiently create and add several new HTML elements to the DOM using a DocumentFragment, minimizing reflows and improving performance.

function createAndAppendItems(parentElementId, itemCount) {
  const parentElement = document.getElementById(parentElementId);
  if (!parentElement) {
    console.error('Parent element not found.');
    return;
  }

  const fragment = document.createDocumentFragment();

  for (let i = 0; i < itemCount; i++) {
    const li = document.createElement('li');
    li.textContent = `Item ${i + 1}`;
    li.style.color = i % 2 === 0 ? 'blue' : 'green'; // Example styling
    fragment.appendChild(li);
  }

  parentElement.appendChild(fragment);
  console.log(`${itemCount} items appended to #${parentElementId}`);
}

// Example Usage:
// Assume you have an empty <ul> with id="myList" in your HTML
// <ul id="myList"></ul>
// createAndAppendItems('myList', 100);
How it works: This snippet demonstrates how to efficiently add a large number of elements to the DOM. Instead of appending each element individually to the live DOM, which can trigger multiple reflows and repaints, it uses a `DocumentFragment`. Elements are first appended to this lightweight, off-screen fragment. Once all elements are added to the fragment, the fragment itself is appended to the target parent element in a single DOM operation, significantly improving performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs