Insert a node using appendchild () and insertbefore () will be returned to the inserted node,
// Because both methods operate on the child nodes of a node, the parent node must be obtained now. somenode in the Code indicates the parent node // use appendchild () method To insert a node var returnednode = somenode. appendchild (newnode); alert (returnednode = newnode) // true // use the insertbefore () method to insert the node var returnednode = somenode. appendchild (newnode); alert (returnednode = newnode) // true
It is worth noting that if the node inserted by the two methods already exists in the Document Tree, the node will be moved to a new location instead of being copied.
<div id="test"><div>adscasdjk</div> <div id="a">adscasdjk</div></div><script type="text/javascript">var t = document.getElementById("test");var a = document.getElementById('a');//var tt = a.cloneNode(true);t.appendChild(a);</script>
In this Code, the page output result is the same as that without JavaScript, And the element is not copied. Because the element is in the last position, it is the same as no operation. If you change the positions of the two child element vertices of the element with ID test, you can see in firbug that the two divs have been replaced.
If we want to copy an element with ID a and add it to the document, the copied element must be removed from the document stream. In this way, the added and copied nodes will not affect the original nodes in the document flow after they are added to the document. That is, we can place the copied elements anywhere in the document without affecting the copied elements. The clonenode () method is used below to implement deep replication of nodes. nodes copied using this method will be out of the Document Stream. Of course, I do not recommend using this method to copy elements with the ID attribute. Because the id value in the document is unique.
<div id="test"><div>adscasdjk</div> <div id="a">adscasdjk</div></div><script type="text/javascript">var t = document.getElementById("test");var a = document.getElementById('a');var tt = a.cloneNode(true);t.appendChild(tt);</script>
Similarly, removenode (node) deletes a node and returns this section. replacenode (newnode, node) replaces the node and returns this node. These two methods are relatively easier to use.