Js AppendChild versus insertBefore in detail

  • 2020-03-30 00:55:50
  • OfStack

We know that appendChild and insertBefore both have the function of inserting nodes. But in application, there are some differences between the two.

For example, when we want 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 this (please comment a different way when testing a situation) :


<script type="text/javascript"> 
var oTest = document.getElementById("test"); 
var newNode = document.createElement("p"); 
newNode.innerHTML = "This is a test"; 
//The test starts here
//The appendChild method:
oTest.appendChild(newNode); 
//InsertBefore method:
oTest.insertBefore(newNode,null); 
</script>

With the above code, you can test that a new node is created under the node div and that the node is the last node in the div. To view the DOM, IE can be viewed through the IE Developer Toolbar plug-in, and Firefox can use Firebug.

Obviously, from this example, you know that appendChildhild and insertBefore can both insert nodes.

In the above example there is a line of code: otest.insertbefore (newNode,null), where insertBefore has two parameters to set, the first is the same as appendChild, the second is unique to it. Not only can it be null, but it can also be:


<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

Or again:


<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 of the x1 node

Can also be 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 will insert a new node in front of the first child node, also by changing the childNodes[0,1,...] To insert a new node somewhere else

Since you can see that the insertBefore() method's property is to insert a new node in front of an existing child node, the insertBefore() method can also be used in example 1 to insert a new node at the end of the child node list. The two cases are combined to find that the insertBefore() method inserts a node anywhere in the list of child nodes.

From these examples:
The appendChild() method adds a new child node at the end of the node's list of children.
The insertBefore() method inserts a new node at any point in the list of children of the node.


Related articles: