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 +, and Opera 7.0 +
Add a node to the child node array of the specified node. It seems to be a bit difficult to read. Simply put, add the element to the specified node.
AppendChild usage
Target. appendChild (newChild)
Insert newChild as the target subnode after the last subnode
AppendChild example
Copy codeThe Code is 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 inserts a new child node before an existing child node.
The insertBefore () method is used to insert a new subnode before an existing subnode.
InsertBefore usage
Target. insertBefore (newChild, existingChild)
NewChild acts as the target subnode before being inserted to the existingChild Node
ExistingChild is an optional parameter. If it is null, the effect is the same as that of appendChild.
InsertBefore example
Copy codeThe Code is 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, should there be insertBefore and insertAfter?
Well, let's use Aptana to compile an example. But the smart prompts of Aptana tell me that there is actually no insertAfter method.
Then define a Luo :)
InsertAfter Definition
Copy codeThe Code is 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 codeThe Code is as follows:
Var txtName = document. getElementById ("txtName ");
Var htmlSpan = document. createElement ("span ");
HtmlSpan. innerHTML = "This is a test ";
InsertAfter (htmlSpan, txtName );
Insert htmlSpan as the brother node of txtName to the txtName node.
Summary:
1. appendChild and insertBefore are used on nodes, while insertAfter is just a UDF.
2. Compared with appendChild, insertBefore can insert new nodes to any position in the array of child nodes of the target node.
3. Use appendChild and insertBefore to insert a new node. The premise is that the sibling node must have a common parent node.