JAVASCRIPT

Efficiently Create and Append Multiple Elements

Learn how to dynamically create several new HTML elements and append them to the DOM efficiently using a DocumentFragment, minimizing browser reflows and improving performance.

function createAndAppendMultiple(parentElementId, itemCount) {
  const parentElement = document.getElementById(parentElementId);
  if (!parentElement) {
    console.error(`Parent element with ID '${parentElementId}' not found.`);
    return;
  }

  const fragment = document.createDocumentFragment();

  for (let i = 0; i < itemCount; i++) {
    const newDiv = document.createElement('div');
    newDiv.textContent = `Item ${i + 1}`;
    newDiv.className = 'dynamic-item';
    fragment.appendChild(newDiv);
  }

  parentElement.appendChild(fragment);
}

// Example usage:
// Assume there's a div with id='container' in your HTML
// <div id="container"></div>
createAndAppendMultiple('container', 100);
How it works: This snippet demonstrates how to efficiently add a large number of elements to the DOM using a `DocumentFragment`. Instead of appending each new element directly to the live DOM in a loop (which can trigger costly reflows for each append), elements are first appended to an in-memory `DocumentFragment`. Once all desired elements are added to the fragment, the fragment itself is appended to the DOM. This results in only a single reflow, significantly improving performance for bulk DOM manipulations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs