1, AppendChild and InsertBefore are the methods used to do the node, and InsertAfter is just a custom function
2, InsertBefore relative to the appendchild, it is more flexible to insert a new node into the target node array in any location.
3, the use of appendchild and insertbefore to insert a new node if the sibling node must have a common parent node
AppendChild definition
AppendChild (Newchild:node): node
Appends a node to the ChildNodes array for the node.
Supported:ie 5.0+, Mozilla 1.0+, Netscape 6.0+, Safari 1.0+, opera 7.0+
Adding a node to an array of child nodes of the specified node is a bit of a mouthful to read, simply to add the element to the specified node
AppendChild usage
Target.appendchild (newchild)
Newchild inserts the last child node as a child node of target
appendchild Example
Copy code code as follows:
var newelement = document.document.createelement (' label ');
Newelement.element.setattribute (' value ', ' username: ');
var usernametext = Document.document.getelementbyid (' username ');
Usernametext.appendchild (newelement);
InsertBefore definition
The InsertBefore () method is inserts a new child node before of existing child node.
The InsertBefore () method works by inserting a new child node before an existing child node
InsertBefore usage
Target.insertbefore (Newchild,existingchild)
Newchild is inserted before the Existingchild node as the child node of target
Existingchild is an optional argument, and when null, the effect is the same as AppendChild
InsertBefore Example
Copy code code as follows:
var otest = document.getElementById ("test");
var newnode = document.createelement ("P");
newnode.innerhtml = "This is a test";
Otest.insertbefore (Newnode,otest.childnodes[0]);
Well, then there should be a insertbefore, InsertAfter, right?
Well, let's write an example with Aptana, but Aptana's smart tip tells me there's no insertafter this method.
Then define a ROM yourself:
InsertAfter definition
Copy code code as follows:
function InsertAfter (newel, Targetel)
{
var parentel = Targetel.parentnode;
if (Parentel.lastchild = = Targetel)
{
Parentel.appendchild (NEWEL);
}else
{
Parentel.insertbefore (newel,targetel.nextsibling);
}
}
InsertAfter Usage and examples
Copy code code as follows:
var txtname = document.getElementById ("txtname");
var Htmlspan = document.createelement ("span");
htmlspan.innerhtml = "This is a test";
InsertAfter (Htmlspan,txtname);
After inserting Htmlspan as the sibling of the txtname to the Txtname node