revision:
The createDocumentFragment() method creates a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree.
The createDocumentFragment() method creates an offscreen node, which can be used to build a new document fragment that can be insert into any document.
The createDocumentFragment() method can also be used to extract parts of a document, change, add, or delete some of the content, and insert it back to the document.
document.createDocumentFragment()
Parameters: none
const fragment = new DocumentFragment();
<div> <ul id="ul"></ul> </div> <script> const element = document.getElementById("ul"); // assuming ul exists const fragment = document.createDocumentFragment(); const browsers = ["Firefox", "Chrome", "Opera", "Safari"]; browsers.forEach((browser) => { const li = document.createElement("li"); li.textContent = browser; fragment.appendChild(li); }); element.appendChild(fragment); </script>
<div> <ul id="myList"> </ul> </div> <script> const fruits = ["Banana", "Orange", "Mango"]; // Create a document fragment: const dFrag = document.createDocumentFragment(); for (let x in fruits) { const li = document.createElement('li'); li.textContent = fruits[x]; dFrag.appendChild(li); } // Add fragment to a list: document.getElementById('myList').appendChild(dFrag); </script>
<div> <ul id="myList2"> <li>Apple</li> <li>Pear</li> </ul> </div> <script> const fruits1 = ["Banana", "Orange", "Mango"]; // Create a document fragment: const dFrag1 = document.createDocumentFragment(); for (let x in fruits1) { const li = document.createElement('li'); li.textContent = fruits1[x]; dFrag1.appendChild(li); } // Add fragment to a list: document.getElementById('myList2').appendChild(dFrag1); </script>