JAVASCRIPT

Efficiently Adding Multiple DOM Elements with DocumentFragment

Learn to create and append multiple new DOM elements efficiently using DocumentFragment to minimize reflows and repaints, improving web performance.

function addItemsEfficiently(containerId, items) {
  const container = document.getElementById(containerId);
  if (!container) return;

  const fragment = document.createDocumentFragment();

  items.forEach(itemText => {
    const li = document.createElement('li');
    li.textContent = itemText;
    fragment.appendChild(li);
  });

  container.appendChild(fragment);
}

// Example Usage:
// Assume you have <ul id="myList"></ul> in your HTML
// addItemsEfficiently('myList', ['Item 1', 'Item 2', 'Item 3']);
How it works: This snippet demonstrates how to create and append multiple DOM elements efficiently using a `DocumentFragment`. Instead of appending each new element directly to the live DOM (which can cause multiple reflows and repaints), elements are first appended to an in-memory `DocumentFragment`. Once all elements are added to the fragment, the fragment itself is appended to the target container in a single operation, significantly improving performance for bulk DOM updates.

Need help integrating this into your project?

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

Hire DigitalCodeLabs