JAVASCRIPT
Efficiently Append Multiple Elements with DocumentFragment
Optimize DOM manipulation performance by appending multiple new elements at once using a DocumentFragment, reducing reflows and repaints for smoother UI updates.
const appendMultipleElements = (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(itemText => {
const li = document.createElement('li');
li.textContent = itemText;
fragment.appendChild(li);
});
parent.appendChild(fragment);
console.log(`${items.length} items appended to '${parentId}'.`);
};
// Example Usage:
// HTML: <ul id="myList"></ul>
// const data = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
// appendMultipleElements('myList', data);
How it works: This function demonstrates how to efficiently add a large number of elements to the DOM. Instead of appending each new `<li>` element directly to the parent `<ul>` one by one (which would cause multiple reflows and repaints), it uses a `DocumentFragment`. Elements are first appended to this lightweight, off-DOM container, and then the entire fragment is appended to the actual DOM in a single operation, significantly improving performance.