XML DOM insertBefore() Method

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 be inserted.
existing_node Required. Existing node. Insert a new node before this node.

Tips and Notes:

Note:Internet Explorer ignores the whitespace text nodes generated between nodes (such as newline characters), while Mozilla does not. Therefore, in the following example, we use a function to check the node type of the last child node.

The node type of an element node is 1, so if the last child node is not an element node, it moves to the previous node and checks whether this node is an element node. This process continues until the last child node that is an element node is found. By this method, the correct result is obtained in both Internet Explorer and Mozilla.

For more information about the differences between IE and Mozilla browsers, please visit the XML DOM tutorial on CodeW3C.com. DOM Browser in this section.

Example

In all the examples, we will use the XML file books.xml, as well as the JavaScript function loadXMLDoc().

The following code snippet creates a new <book> element and inserts it before the last <book> element in the document:

//check if the last childnode is an element node
function get_lastchild(n)
{
x=n.lastChild;
while (x.nodeType!=1)
  {
  x=x.previousSibling;
  }
return x;
}
xmlDoc=loadXMLDoc("books.xml");
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");
newTitle.appendChild(newText);
newNode.appendChild(newTitle);
xmlDoc.documentElement.insertBefore(newNode,get_lastchild(x));