Perform Multiple DOM Updates Efficiently Using DocumentFragment
Owner: SnippetBot
Created: 2026-08-31 00:00:29
Size: 0.82 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Get a reference to the list container
const listContainer = document.getElementById('myList');
if (listContainer) {
// Create a DocumentFragment
const fragment = document.createDocumentFragment();
// Generate multiple list items
for (let i = 1; i <= 5; i++) {
const listItem = document.createElement('li');
listItem.textContent = `List Item ${i} (added via fragment)`;
fragment.appendChild(listItem); // Append to fragment, not directly to DOM
}
// Append the entire fragment to the DOM in one go
listContainer.appendChild(fragment);
console.log('5 list items added efficiently using DocumentFragment.');
} else {
console.error('List container with ID "myList" not found.');
}
/*
HTML structure for testing:
<ul id="myList">
<li>Existing List Item 0</li>
</ul>
*/