A piece of code about the confusion of DocumentFragment

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
            <input type="text" id="a">
            <span id="b">222</span>
    </div>
    <div id="ap">

    </div>
<script>
    function nodetofragment(node){
        let n = 0
        var flag = document.createDocumentFragment();
        var child;
        while(child = node.firstChild){
            flag.appendChild(child)
            console.log(nPP)
        }
        return flag;
    }
    var dom = nodetofragment(document.getElementById("app"))
    console.log(dom);
</script>
</body>
</html>

after four while loops in this code, I don"t understand why, and the loop conditions of while are not very clear.
after the execution of this code, the input and span in the page disappear.
execution result:

clipboard.png

Wanwang solution

Mar.01,2021

understands that the appendchild method moves dom nodes


first of all, you should understand the influence of the appendChild method: the appendChild method actually adds the node to the children of the target Node (in this case, DocumentFragment ), if your node is already rendered on the HTML page, it will actually be removed and added to the target Node, so that you can loop here.
so why did it loop five times? it's very simple because the Node node types of HTML are divided into:

NodeType

Yes, there is a space separation in your HTML , so there is a text node of type TEXT_NODE

.
Menu