XML DOM insertBefore() Method


❮ Element Object

Example

The following code fragment loads "books.xml" into xmlDoc, creates a new <book> node and inserts it before the last <book> element:

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 an existing child node.

This method returns the new child node.

Syntax

elementNode.insertBefore(new_node,existing_node)

Parameter Description
new_node Required. The node to insert
existing_node Required. The existing node. The new node is inserted before this node.

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