XML DOM insertBefore() Method
Definition and Usage
The insertBefore() method can insert a new child node before an existing child node.
This method can return the new child node.
Syntax:
insertBefore(newchild, refchild)
Parameters | Description |
---|---|
newchild | Insert a new node |
refchild | Insert a new node before this node |
Tips and Notes
Note:Internet Explorer will ignore the whitespace text nodes generated between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following examples, we will 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 first child node is not an element node, it will move to the next node and continue to check whether this node is an element node. This process will continue until the first element child node is found. Through this method, we can get the correct method in Internet Explorer and Mozilla.
Tip:For more information on the differences between XML DOM in IE and Mozilla browsers, please visit our DOM Browser Chapter.
Example
In all examples, we will use XML files books.xmland the JavaScript function loadXMLDoc().
The following snippet can create a new <book> node and insert this node before the last <book> element in the document:
//check if the last childnode is an element node
function get_lastchild(n)
{
var x=n.lastChild;
while (x.nodeType!=1)
{
x=x.previousSibling;
return x;
xmlDoc=loadXMLDoc("books.xml");
var newNode=xmlDoc.createElement("book");
var newTitle=xmlDoc.createElement("title");
var newText=xmlDoc.createTextNode("A Notebook");
newTitle.appendChild(newText);
newNode.appendChild(newTitle);
xmlDoc.documentElement.insertBefore(newNode,get_lastchild(x));