JAVASCRIPT

Efficiently Updating Multiple Elements with DocumentFragment

Improve performance when adding many DOM elements by using DocumentFragment to minimize reflows and repaints in the browser.

function populateListEfficiently(listId, items) {
  const listElement = document.getElementById(listId);
  if (!listElement) {
    console.error(`List element with ID '${listId}' not found.`);
    return;
  }

  const fragment = document.createDocumentFragment();

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

  // Clear existing items if any (optional, depends on use case)
  listElement.innerHTML = '';

  listElement.appendChild(fragment);
}

// Example Usage:
// HTML to go with this: <ul id="myList"></ul>
const dataItems = ['Item One', 'Item Two', 'Item Three', 'Item Four', 'Item Five'];
populateListEfficiently('myList', dataItems);

// To append additional items without clearing:
// const moreItems = ['New Item Six', 'New Item Seven'];
// const fragment2 = document.createDocumentFragment();
// moreItems.forEach(itemText => {
//   const listItem = document.createElement('li');
//   listItem.textContent = itemText;
//   fragment2.appendChild(listItem);
// });
// document.getElementById('myList').appendChild(fragment2);
How it works: When adding a large number of elements to the DOM, repeatedly appending directly to an existing element can be slow due to frequent browser reflows and repaints. This snippet demonstrates using a `DocumentFragment`. Elements are first created and appended to the fragment, which is an lightweight, in-memory container. Once all elements are added to the fragment, the entire fragment is appended to the live 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