InsertBefore ()
Grammar:
InsertBefore (Newchild,refchild)
Newchild Inserting a new node
Refchild inserting a new node before this node
<ul id= "MyList" >
<li>Coffee</li>
<li>Tea</li>
</ul>
function MyFunction () {
var newitem=document.createelement ("LI")
var textnode=document.createtextnode ("Water")
Newitem.appendchild (Textnode)
var List=document.getelementbyid ("MyList")
List.insertbefore (Newitem,list.childnodes[0]);
}
AppendChild ()
Grammar:
AppendChild (newchild)
Newchild the nodes that are added
<ul id= "MyList" >
<li>Coffee</li>
<li>Tea</li>
</ul>
function MyFunction () {
var node=document.createelement ("LI");
var textnode=document.createtextnode ("Water");
Node.appendchild (Textnode);
document.getElementById ("MyList"). appendchild (node);
}
JS write basic InsertAfter () method
Dom does not provide a InsertAfter () method
function InsertAfter (newelement, targetelement) {
var parent = Targetelement.parentnode;
if (Parent.lastchild = = targetelement) {
If the last node is the target element, it is added directly. Because the default is the last
Parent.appendchild (newelement);
}else {
Parent.insertbefore (newelement, targetelement.nextsibling);
If it is not, it is inserted in front of the next sibling node of the target element. Which is behind the target element.
}
}
JS Inserts a new node