HTML DOM createDocumentFragment() method


The HTML DOM createDocumentFragment() method is used for creating a document fragment. The document fragment doesn’t affect the DOM structure as it resides in memory. When we append the document fragment to the DOM, it is basically replaced by its children i.e there is no document fragment appended to the document only its children gets appended.

Syntax

Following is the syntax for the createDocumentFragment() method −

document.createDocumentFragment()

It returns a DocumentFragment object, representing the documentFragment node.

Example

Let us look at an example for the HTML DOM createDocumentFragment() method −

Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>createDocumentFragment() example</h1>
<p>Click the below button to change list items using the createDocumentFragment method.</p>
<button type="button" onclick="changeList()">CHANGE</button>
<ul>
<li>Mango</li>
<li>Peach</li>
<li>Guava<li>
<li>Strawberry</liv
<li>Papaya</li>
</ul>
<script>
   function changeList() {
      var x= document.createDocumentFragment();
      x.appendChild(document.getElementsByTagName("LI")[0]);
      x.childNodes[0].childNodes[0].nodeValue = "Watermelon";
      document.getElementsByTagName("UL")[0].appendChild(x);
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button −

In the above example −

We have created an unordered list with five list items −

<ul>
<li>Mango</li>
<li>Peach</li>
<li>Guava<li>
<li>Strawberry</li>
<li>Papaya</li>
</ul>

We have then created CHANGE button that will execute the changeList() method on being clicked by the user −

<button type="button" onclick="changeList()">CHANGE</button>

The changeList() function creates a document fragment using the createDocumentFragment() method of the document object and assigns it to the variable x. Using the appnedChild() method we make the list element the child of the document fragment. We set the first list element value that is inside the document fragment to “Watermelon”. We then append the document fragment as the last child of the

function changeList() {
   var x= document.createDocumentFragment();
   x.appendChild(document.getElementsByTagName("LI")[0]);
   x.childNodes[0].childNodes[0].nodeValue = "Watermelon";
   document.getElementsByTagName("UL")[0].appendChild(x);
}

Updated on: 20-Feb-2021

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements