We know that both appendchild and InsertBefore have the ability to insert nodes. But in the application, there are some differences between the two.
For example, if we were to insert a child node p in the following div:
<div id= "test" ><p id= "x1" >Node</p><p>Node</p></div>
We can write it this way (when testing a situation, add another note):
Copy Code code as follows:
<script type= "Text/javascript" >
var otest = document.getElementById ("test");
var newNode = document.createelement ("P");
newnode.innerhtml = "This is a test";
The test starts here.
AppendChild Method:
Otest.appendchild (NewNode);
InsertBefore Method:
Otest.insertbefore (Newnode,null);
</script>
Through the above code, you can test that a new node is created under the node Div, and that the node is the last div node. (If you want to see Dom,ie can be viewed through the IE Developer Toolbar plugin, Firefox can use Firebug)
Obviously, with this example, you know that Appendchildhild and insertbefore can be inserted into the node operation.
In the above example there is a code: Otest.insertbefore (Newnode,null), where InsertBefore has 2 parameters can be set, the first is the same as AppendChild, and the second is unique. Not only can it be null, but it can also be:
Copy Code code as follows:
<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>
This example inserts a new node in front of the X1 node
Also or:
Copy Code code as follows:
<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>
This example inserts a new node in front of the next node in the X1 node
can also be:
Copy Code code as follows:
<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>
This example inserts a new node in front of the first child node, or by changing the childnodes[0,1,...] To insert a new node in another location
Because the attribute of the Visible insertbefore () method is to insert a new node in front of an existing child node, the InsertBefore () method can also be used to insert the new node at the end of the list of child nodes. In combination, it is found that the InsertBefore () method inserts a node, which can be anywhere in the child node list.
From the following examples:
The AppendChild () method adds a new child node at the end of the node's child node list.
The InsertBefore () method inserts a new node at any point in the node's child node list.