JAVASCRIPT

Efficiently Add Multiple Elements Using DocumentFragment

Discover how to use DocumentFragment to group multiple new DOM elements, minimizing reflows and improving performance when adding them to the page.

const fragment = document.createDocumentFragment();

for (let i = 0; i < 10; i++) {
  const listItem = document.createElement('li');
  listItem.textContent = `List Item ${i + 1}`;
  fragment.appendChild(listItem);
}

const myList = document.getElementById('myList');
if (myList) {
  myList.appendChild(fragment);
}
How it works: This code shows how to use a `DocumentFragment` to efficiently add multiple elements to the DOM. Instead of appending each `<li>` directly to the `<ul>` (which would trigger multiple reflows), all `<li>` elements are first appended to the `DocumentFragment`. Once all elements are in the fragment, the entire fragment is appended to the `<ul>`. This results in only one DOM manipulation and reflow, significantly improving performance for large lists.

Need help integrating this into your project?

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

Hire DigitalCodeLabs