XML DOM insertBefore() Method


❮ Node Object

Example

The following code fragment 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;
}

The output of the code above will be:

Book elements before: 4
Book elements after: 5
Try it Yourself »

Definition and Usage

The insertBefore() method inserts a new child node before a specified child node of the current node.

Note: If the newchild is already in the tree, it is first removed.


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The insertBefore() method is supported in all major browsers.


Syntax

nodeObject.insertBefore(newchild,existingnode)

Parameters

Parameter Type Description
newchild Node object Required. The new child node to insert
existingnode Node object Required. The node to insert the new child node before. If existingnode is null, insert newchild at the end of the list of children

Return Value

Type Description
Node object The inserted node

Technical Details

DOM Version Core Level 1 Node Object. Modified in DOM Level 3

❮ Node Object
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.