Build subtrees with DocumentFragment
Quick answer
A DocumentFragment is a container for nodes outside the document tree. Inserting the fragment moves its children into the destination, leaving the fragment empty. It is useful for organizing construction, not a universal performance guarantee.
Browser example
Run in a browser document, not a bare Node.js process.
const f=document.createDocumentFragment();f.append(document.createElement("li"),document.createElement("li"));const ul=document.createElement("ul");ul.append(f);console.log(f.childNodes.length,ul.children.length);Expected console output:
0 2Common mistake
The fragment itself is not inserted as an element.
Practice
Build three list items in a fragment and transfer them to a list.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Build subtrees with DocumentFragment — Knowledge Check
Check the central concept, apply it to a new scenario, and predict browser behavior.
What remains in a fragment after all its children are inserted?
Why assemble several elements in a DocumentFragment?
After appending a fragment, what happens to the parent of its former child?
Can an emptied fragment be used to assemble another group of nodes?
What is printed by this browser snippet? (Build subtrees with DocumentFragment)
const f=document.createDocumentFragment();const p=document.createElement("div");f.append(document.createElement("i"),"text");p.append(f);console.log(f.childNodes.length,p.childNodes.length,p.children.length);