The two methods are understood first from the definition:
AppendChild () Method: You can add a new child node to the end of the node's child nodes list. Syntax: AppendChild (newchild)
InsertBefore () Method: You can insert a new child node before the existing child node. Syntax: InsertBefore (Newchild,refchild)
The same: Insert child nodes
Differences: The principle and method of implementation are different.
The AppendChild method is to add a new node (relative to the parent node) at the end of the child node in the parent node.
The InsertBefore method is to add a new node (relative to the child node) before the existing node.
Take a look at this simple example: Add a child node div at the end of ID Box-con
<div class= "Btns" ><input type= "button" value= "Insert Element" id= "CREATBTN"/></div>
<div id= "Box-one" >
<p class= "Con2" id= "P1" >1</p>
<p class= "Con2" >2</p>
<p class= "Con2" >3</p>
</div>
Window.onload =function () {
var btn = document.getElementById ("creatbtn");
Btn.onclick =function () {
Insertele ();
}
}
function Insertele () {
var otest = document.getElementById ("Box-one");
var newNode = document.createelement ("div");
newnode.innerhtml = "This is a Newcon";
Otest.appendchild (NewNode);
Oteset.insertbefore (Newnode,null); Both of these methods can be implemented
}
The first parameter of this insertbefore is the same as the appendchild, which is the new node variable, and the insert second parameter can be not only null. It can be written like this.
function Insertele () {
var otest = document.getElementById ("Box-one");
var newNode = document.createelement ("div");
var reforenode = document.getElementById ("P1");
newnode.innerhtml = "This is a Newcon";
Otest.insertbefore (Newnode,reforenode); The newly created element node is inserted in front of the element with ID p1
}
Or
function Insertele () {
var otest = document.getElementById ("Box-one");
var newNode = document.createelement ("div");
var reforenode = document.getElementById ("P1");
newnode.innerhtml = "This is a Newcon";
Otest.insertbefore (newnode,reforenode.nextsibling);//The newly created element node is inserted in front of the node element with ID p1.
This means that the insertion ID is behind the P1 node element.
}
What you want to say here is nextSibling: the element immediately following an element (in the same tree hierarchy).
Reforenode.nextsibling: Gets the next node immediately following the Reforenode object.
PreviousSibling-Gets the previous sibling node of a node
Because the attribute of the Visible insertbefore () method is to insert a new node in front of an existing child node but both cases are combined to find that the insertbefore () method is inserted into the node, which can be anywhere in the list of child nodes.
JS Insert node appendchild and InsertBefore