XML DOM » Node » insertBefore

Syntax:
node.insertBefore(newChild, refChild)

This method is used to insert a new child node before an existing one. If no child node exists, the new child node becomes the first.

All the nodes involved in the operation must be compatible; i.e. the reference node must be a child node of this node, and the new node must be writeable and of a type that can be a child node to it (See the list of Node Types). If the new child node is a DocumentFragment all its children are inserted before the ref node in the same order, and if the node already exists, then it is first removed.

Examples

Code:
XML:

<names>
   <name>Alice</name>
   <name>Bert</name>
   <name>Charlie</name>
   <name>Diane</name>
   <name>Eric</name>
</names>

JavaScript:

var xml_doc = new
ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.load("names.xml");

var new_node = xml_doc.createElement("name");
var new_text = xml_doc.createTextNode("Cathy");
new_node.appendChild(new_text);
var root = xml_doc.documentElement;
root.insertBefore(new_node, root.childNodes.item(2));

var names = xml_doc.getElementsByTagName("name");
var i, n_names = names.length;
for (i = 0; i < n_names; i++)
   document.write(names[i].firstChild.nodeValue + "<br>");
Output:
Alice
Bert
Cathy
Charlie
Diane
Eric Eric
Explanation:

This uses the 'names.xml' file and creates a new 'name' element and a text node with the value of 'Cathy' which is appended to it. The new 'name' element is then inserted into the document root's list of children before the third element ('Charlie'). Then a NodeList collection is created of all the 'name' elements, and the code iterates through it displaying the value of the first child of each (the text node).

Language(s): JavaScript XML