JAVASCRIPT

Efficiently Append Multiple Elements Using DocumentFragment

Optimize DOM updates by creating and appending multiple elements simultaneously using DocumentFragment. This reduces reflows and repaints, improving web application performance.

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

  const fragment = document.createDocumentFragment();

  items.forEach((item, index) => {
    const li = document.createElement('li');
    li.textContent = item;
    li.setAttribute('data-index', index);
    fragment.appendChild(li);
  });

  parent.appendChild(fragment);
}

// Example usage:
// <ul id="myList"></ul>
// const data = ['Item A', 'Item B', 'Item C', 'Item D'];
// appendMultipleElementsEfficiently('myList', data);
How it works: When adding many elements to the DOM, directly appending them one by one can be slow due to repeated reflows and repaints. This snippet uses `document.createDocumentFragment()` to create a lightweight container. Elements are appended to this fragment, which is then appended to the actual DOM in a single 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