How To Use CreateDocumentFragment Method In JavaScript

admin_img Posted By Bajarangi soft , Posted On 25-09-2020

In Java Script we can change or append list of items onclick of button using createdocumentfragment method, so today we going to discuss how to use createdocumentfragment method in java script

How To Use CreateDocumentFragment Method In JavaScript

The createDocumentFragment() method creates an imaginary Node object, with all the properties and methods of the Node object.

The createDocumentFragment() method is usefull when you want to extract parts of your document, change, add, or delete, some of the content, and insert it back to your document.

You can also use the document's Document object to perform these changes, but to prevent destroying the document structure, it can be safer to extract only parts of the document, make the changes, and insert the part back to the document.

Note: Nodes being appended to the document fragment, from the document, will be removed from the document.

Syntax and Usage

document.createDocumentFragment()


Example(1)

        <button class="btn btn-primary" onclick="append_list()">Click it</button>
   
<script>
    function append_list() {
        var d = document.createDocumentFragment();
        d.appendChild(document.getElementsByTagName("LI")[0]);
        d.childNodes[0].childNodes[0].nodeValue = "JAVA SCRIPT";
        document.getElementsByTagName("UL")[0].appendChild(d);
    }
</script>


In above example creating a documentFragment node and append a child to it (a list item). Then, change the list item's node value and insert it as the last child of the list


Complete code for createdocumentfragment method in java script

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM CreateDocumentFragment Method In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
    li{
        font-size: 50px;
    }
</style>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>HTML DOM CreateDocumentFragment Method In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        <ul>
            <li>PHP</li>
            <li>LARAVEL</li>
            <li>PYTHON</li>
            <li>JAVA</li>
        </ul>
        <button class="btn btn-primary" onclick="append_list()">Click it</button>
    </div>
    <br>
</div>
</body>
</html>
<script>
    function append_list() {
        var d = document.createDocumentFragment();
        d.appendChild(document.getElementsByTagName("LI")[0]);
        d.childNodes[0].childNodes[0].nodeValue = "JAVA SCRIPT";
        document.getElementsByTagName("UL")[0].appendChild(d);
    }
</script>

 

Related Post