We know that both appendchild and insertbefore have the function of inserting nodes. However, there are some differences between the two in terms of applications.
For example, when we want to insert a subnode P in the following Div:
<Div id = "test"> <p id = "X1"> node </P> <p> node </P> </div>
We can write it like this (in some cases, add another comment ):
<SCRIPT type = "text/JavaScript">
VaR otest = Document. getelementbyid ("test ");
VaR newnode = Document. createelement ("p ");
Newnode. innerhtml = "this is a test ";
// The test starts from here.
// Appendchild method:
Otest. appendchild (newnode );
// Insertbefore method:
Otest. insertbefore (newnode, null );
</SCRIPT>
Through the above code, we can test that a new node is created under the node Div, and this node is the last node of the div. (For Dom viewing, ie can be viewed through the IE developer toolbar plug-in, Firefox can use firebug)
Obviously, through this example, we can know that both appendchildhild and insertbefore can be used to insert nodes.
In the above example, there is a code: otest. insertbefore (newnode, null). Here, insertbefore has two parameters that can be set. The first parameter is the same as appendchild, but the second parameter is unique to it. It can be either null or:
<SCRIPT type = "text/JavaScript">
VaR otest = Document. getelementbyid ("test ");
VaR refchild = Document. getelementbyid ("X1 ");
VaR newnode = Document. createelement ("p ");
Newnode. innerhtml = "this is a test ";
Otest. insertbefore (newnode, refchild );
</SCRIPT>
In this example, a new node is inserted before the X1 node.
Or:
<SCRIPT type = "text/JavaScript">
VaR otest = Document. getelementbyid ("test ");
VaR refchild = Document. getelementbyid ("X1 ");
VaR newnode = Document. createelement ("p ");
Newnode. innerhtml = "this is a test ";
Otest. insertbefore (newnode, refchild. nextsibling );
</SCRIPT>
In this example, a new node is inserted before the next node of the X1 node.
It can also be:
<SCRIPT type = "text/JavaScript">
VaR otest = Document. getelementbyid ("test ");
VaR newnode = Document. createelement ("p ");
Newnode. innerhtml = "this is a test ";
Otest. insertbefore (newnode, otest. childnodes [0]);
</SCRIPT>
In this example, a new node is inserted before the first subnode. You can also insert a new node in another location by changing childnodes [,...].
As you can see, the insertbefore () method inserts a new node before an existing subnode. However, in the example 1, The insertbefore () method can also be used to insert a new node at the end of the subnode list. The two conditions are combined to find that the insertbefore () method can insert nodes anywhere in the subnode list.
The following examples show that:
Appendchild () method adds a new subnode at the end of the subnode list of the node.
The insertbefore () method inserts a new node anywhere in the node's subnode list.