HTML DOM Document createDocumentFragment() Method
- Previous Page createComment()
- Next Page createElement()
- Go to Parent Layer HTML DOM Documents
Definition and Usage
createDocumentFragment()
The method creates an offscreen node.
Offscreen nodes can be used to build a new document fragment that can be inserted into any document.
createDocumentFragment()
The method can also be used to extract part of the document content, make changes, add or delete some content, and insert it back into the document.
Tip
You can always directly edit HTML elements. But a better method is to build (offscreen) document fragments and append this fragment to the real (active) DOM when ready. Since you insert the fragment after it is ready, you will only need one reflow and one render.
If you want to append HTML element items in a loop, using a document fragment can also improve performance.
Note:Document nodes appended to the document fragment will be removed from the original document.
Instance
Example 1
Add elements to an empty list:
const fruits = ["Banana", "Orange", "Mango"]; // Create a document fragment: const dFrag = document.createDocumentFragment(); // Add the li element to the fragment: for (let x in fruits) { const li = document.createElement('li'); li.textContent = fruits[x]; dFrag.appendChild(li); } // Add the fragment to the list: document.getElementById('myList').appendChild(dFrag);
Example 2
Add elements to an existing list:
const fruits = ["Banana", "Orange", "Mango"]; // Create a document fragment: const dFrag = document.createDocumentFragment(); // Add the li element to the fragment: for (let x in fruits) { const li = document.createElement('li'); li.textContent = fruits[x]; dFrag.appendChild(li); } // Add the fragment to the list: document.getElementById('myList').appendChild(dFrag);
Syntax
document.createDocumentFragment()
Parameter
None.
Return value
Type | Description |
---|---|
Node | The newly created DocumentFragment node has no child nodes. |
Browser support
document.createComment()
It is a feature of DOM Level 1 (1998).
All browsers support it:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9-11 | Support | Support | Support | Support |
- Previous Page createComment()
- Next Page createElement()
- Go to Parent Layer HTML DOM Documents