The usage of AppendChild and insertBefore in js is explained in detail


**The appendChild definition **The appendChild (newChild: Node) : the 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 children of the specified node is a mouthful to say, simply adding an element to the specified node

**The appendChild usage **Target. The appendChild (newChild)

The newChild is inserted after the last child node as a child of target

**The appendChild example **Var newElement = document. The document. The createElement method (” label ”); NewElement. Element. The setAttribute (’ value ’, ‘the Username:’);

Var usernameText = document. The document. The getElementById (” username ”); UsernameText. The appendChild (newElement);

**InsertBefore definition **The insertBefore() method inserts a new child node before an existing child node.

The insertBefore() method inserts a new child node in front of an existing child node

**InsertBefore usage **Target. The insertBefore (newChild, existingChild)

The newChild is inserted before the existingChild node as a child of target

ExistingChild is an optional parameter, which is the same as appendChild when null

**InsertBefore example **Var oTest = document. GetElementById (” test ”); Var newNode = document. The createElement method (” p ”); Newnode. innerHTML = “This is a test”;

OTest. InsertBefore (newNode, oTest.childnodes [0]).  

  Ok, so I guess there’s an insertBefore and an insertAfter, right? Ok, so let’s write an example using Aptana, but Aptana’s smart tip tells me that there’s no insertAfter method So define one for yourself :)

**InsertAfter definition **The function insertAfter (newEl, targetEl) {           Var parentEl = targetEl. ParentNode;

          If (parentEl lastChild = = targetEl)           {                     ParentEl. The appendChild (newEl);           } the else           {                     ParentEl. InsertBefore (newEl, targetEl nextSibling);           }                       }

  **InsertAfter usage with examples **Var txtName = document. GetElementById (” txtName ”); Var htmlSpan = document. The createElement method (” span ”); HtmlSpan. InnerHTML = “This is a test”; InsertAfter (htmlSpan txtName);

Insert htmlSpan as a sibling of txtName after the txtName node

**Conclusion: **AppendChild and insertBefore are used as methods on nodes, and insertAfter is just a custom function

InsertBefore is more flexible than appendChild by inserting a new node into any position in the node array of the target node.

AppendChild and insertBefore are used to insert new nodes on the premise that their siblings must have a common parent