A document fragment is a lightweight, separate DOM tree that can hold nodes without rendering as part of the page. It provides a temporary place to assemble content before inserting that content into the document. section 7.2 section 8.2
Use a fragment when you want to build several nodes before adding them to the page:
- Create one with document.createDocumentFragment(). section 7.2
- Append newly created elements to the fragment while constructing the subtree. section 7.2
- Append the fragment to the document once, avoiding repeated direct insertions and their associated DOM recalculation. section 7.2
- Expect its child nodes to move into the document, leaving the fragment itself without those children. section 7.2
Adding five paragraphs
Create a fragment, loop five times to make paragraph elements, append each paragraph to the fragment, and then call document.body.appendChild(fragment). The page receives five sibling paragraphs rather than an extra wrapper element. section 7.2
Listing 7.4. Using a document fragment
<html>
<head>
<title>Document Fragment Demo</title>
</head>
<body>
<script>
const fragment = #1
document.createDocumentFragment();
for (let c = 0; c < 5; c++) {
const li = document.createElement('p');
li.innerText = 'paragraph ' + c;
fragment.appendChild(li); #2
}
document.body.appendChild(fragment); #3
</script>
</body>
</html>
Inspect the complete fragment example, including node creation, repeated fragment appends, and the final document insertion. section 7.2

