XML DOM insertBefore() Method
Definition and Usage
insertBefore()
The method inserts a new child node before the specified child node of the current node.
Note:If newchild is already in the tree, it is first deleted.
Syntax
nodeObject.insertBefore(newchild,existingnode,
)
) | Description |
---|---|
newchild | Required. Node object. The new child node to be inserted. |
existingnode |
Required. Node object. The node before which the new child node is to be inserted. If the existing node is empty, the new child node is inserted at the end of the child node list. |
Technical Details
DOM Version: | Core Level 1 Node Object. Modified in DOM Level 3. |
---|---|
Return value: | Node object. The node to be inserted. |
Example
The following code loads "books.xml", creates a new <book> node, and inserts it before the last <book> node:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var xmlDoc = xml.responseXML; var newNode = xmlDoc.createElement("book"); var x = xmlDoc.documentElement; var y = xmlDoc.getElementsByTagName("book"); document.getElementById("demo").innerHTML = "Book elements before: " + y.length + "<br>"; x.insertBefore(newNode, y[3]); document.getElementById("demo").innerHTML += "Book elements after: " + y.length; }
Browser Support
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support |
All mainstream browsers support insertBefore()
Methods.