The InsertBefore () method inserts a given node in front of a given child node of a given element node and returns a reference pointer to the new child node:
Reference = Element.insertbefore (Newnode,targetnode);
As shown above, the node NewNode will be inserted into the element node elements and appear before the node TargetNode. The node TargetNode must be a child node of element elements. If the TargetNode node is not given, the NewNode node is appended to the last child node of element-----from the effect, which is equivalent to calling the AppendChild () method.
The InsertBefore () method is typically used in conjunction with the createelement () and Createtargetnode () methods to insert the newly created node into the document tree.
In the following example, a document has an id attribute value is a content element, and this element contains an id attribute value is fineprint, we will use the createelement () method to create a new text segment element, Then insert the new element in front of the fineprint element included in the content element:
var container = document.getElement.ById ("content"); var message = document.getElementById ("FinePrint"); var para = document.createelement ("P"); Container.insertbefore (para,message);
If the inserted element itself has child nodes, those child nodes are also inserted into the target node:
var container = document.getElementById ("content"); var message = document.getElementById ("FinePrint"); var para = document.createelement ("P"); var text = document.createTextNode ("Here cones the FinePrint");p ara.appendchild (text); Container.insertbefore (para,message);
The InsertBefore () method can be used not only to insert newly created elements, but also to nudge existing nodes in the document.
In the following example, a document has an ID zodiac value is an element of content, and in this element there is an element that contains an id attribute value that is fineprint, and elsewhere in this document there is an id attribute value that is headline element. After this element is found, the last statement moves the headline element to the front of the fineprint element contained in the content element:
var container = document.getElementById ("content"); var messge = document.getElementById ("FinePrint"); var announcement = document.getElementById ("headline"); Container.insertbefore (announcement,message);
Note that the element with the ID attribute value of headline is removed from the document book first and then reinserted into the new location, which is the fineprint element contained in the content element.
InsertBefore ()