JAVASCRIPT

Efficiently Add Multiple DOM Elements Using DocumentFragment

Learn how to significantly improve performance when adding numerous elements to the DOM by utilizing the DocumentFragment API in JavaScript, minimizing costly reflows and repaints.

function addMultipleElementsEfficiently(containerId, itemCount) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Container with ID '${containerId}' not found.`);
    return;
  }

  const fragment = document.createDocumentFragment();

  for (let i = 0; i < itemCount; i++) {
    const div = document.createElement('div');
    div.textContent = `Item ${i + 1}`;
    div.className = 'list-item'; // Add a class for styling
    fragment.appendChild(div);
  }

  container.appendChild(fragment);
  console.log(`${itemCount} elements added efficiently to #${containerId}.`);
}

// Example usage:
// In your HTML: <div id="myContainer"></div>
// Call it: addMultipleElementsEfficiently('myContainer', 100);
How it works: This snippet demonstrates how to efficiently add a large number of elements to the DOM using `DocumentFragment`. Instead of appending each new element directly to the live DOM, which triggers costly reflows and repaints for every operation, elements are first appended to an in-memory `DocumentFragment`. Once all elements are added to the fragment, the fragment itself is appended to the actual DOM. This results in only one single DOM manipulation, drastically improving performance, especially with many elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs