HTML - DOM Document createDocumentFragment() Method



The createDocumentFragment() method creates a new empty document fragment which resides in memory. It acts like an empty container which holds the DOM elements before inserting into HTML document.

Elements are appended in the newly created document fragment and then this document fragment is appended to DOM tree where document fragment is replaced by all its children. It helps in changing the document's content by adding deleting or modifying a node.

Syntax

document.createDocumentFragment();

Parameter

This method does not accept any parameter.

Return Value

It returns the created document fragment node.

Examples of HTML DOM Document 'createDocumentFragment()' Method

The following examples illustrates use of createDocumentFragment method to add and modify existing elements in list.

Adding Elements to an Empty List

In the following example we will add an element in an empty list by using create createDocumentFragment() method.

<!DOCTYPE html>
<html lang="en">
<head&gt
    <title>
        HTML DOM Document createDocumentx() Method
    </title>
</head&gt
<body>
    <h3>HTML DOM Document createDocumentFragment() Method</h3>
    <ul id="list"></ul>
    <script>
        let list = document.getElementById('list');
        let x = document.createDocumentFragment();
        let cars = ["Tata", "BMW", "Audi"];
        for(const i of cars){
            let item=document.createElement("li");
            item.textContent=i;
            x.appendChild(item);
        }
        list.appendChild(x);
    </script>
</body>
</html>

Modifying the Existing List

In the following example we will modify an existing list using createDocumentFragment() method.

<!DOCTYPE html>
<html lang="en">
<head&gt
    <title>
        HTML DOM Document createDocumentFragment() Method
    </title>
</head&gt
<body>
    <h3>HTML DOM Document createDocumentFragment() Method</h3>
    <button onclick="fun()">Click me</button>
    <ul>
        <li>BMW</li>
        <li>Tesla</li>
        <li>Audi</li>
        <li>Mahindra</li>
        <li>Honda</li>
    </ul>
    <script>
       function fun() {
          let x= document.createDocumentFragment();
          x.appendChild(document.getElementsByTagName("li")[0]);
          x.childNodes[0].childNodes[0].nodeValue ="Tata";
          document.getElementsByTagName("ul")[0].appendChild(x);
        }
    </script>
</body>
</html>

Supported Browsers

Method Chrome Edge Firefox Safari Opera
createDocumentFragment() Yes 1 Yes 12 Yes 1 Yes 1 Yes 12.1
html_dom_document_reference.htm
Advertisements