JAVASCRIPT

Efficiently Appending Multiple Elements with DocumentFragment

Learn how to improve performance when adding numerous elements to the DOM by using DocumentFragment, which minimizes reflows and repaints.

function appendMultipleElementsEfficiently(parentId, items) {
  const fragment = document.createDocumentFragment();
  items.forEach(itemText => {
    const li = document.createElement('li');
    li.textContent = itemText;
    fragment.appendChild(li);
  });
  document.getElementById(parentId).appendChild(fragment);
}

// Example Usage:
// <ul id="myList"></ul>
// appendMultipleElementsEfficiently('myList', ['Item A', 'Item B', 'Item C']);
How it works: This snippet demonstrates how to efficiently add multiple elements to the DOM. Instead of appending each new `li` element directly to the main DOM, which can trigger costly reflows and repaints for each operation, we first append them to a `DocumentFragment`. Once all elements are added to the fragment, the entire fragment 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