← Back to all snippets
JAVASCRIPT

Efficiently Update Multiple DOM Elements with DocumentFragment

Optimize DOM manipulation by using `DocumentFragment` to add multiple elements in a single reflow, reducing performance overhead for large lists or dynamic content.

// Assume an existing container in the HTML: <ul id="myList"></ul>
const listContainer = document.getElementById('myList');

// Create a DocumentFragment
const fragment = document.createDocumentFragment();

// Data to render
const items = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];

// Loop through data and append elements to the fragment
items.forEach(itemText => {
  const listItem = document.createElement('li');
  listItem.textContent = itemText;
  fragment.appendChild(listItem);
});

// Append the DocumentFragment to the actual DOM once
// This triggers only one reflow/repaint, rather than one for each item
listContainer.appendChild(fragment);

// To clear the list and re-add new items
// listContainer.innerHTML = ''; // Clear existing content
// listContainer.appendChild(fragment); // Re-add new content
How it works: When adding multiple elements to the DOM in a loop, each `appendChild()` call can trigger a reflow and repaint, impacting performance. `document.createDocumentFragment()` creates a lightweight, in-memory container that elements can be appended to. Appending the entire fragment to the actual DOM then triggers only a single reflow, significantly improving performance for large updates and complex dynamic content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs