XML DOM previousSibling Property

Node object reference manual

Definition and Usage

The previousSibling property can return the node that precedes a certain node (at the same tree level)

If there is no such node, this property returns null.

Syntax:

nodeObject.previousSibling

Tips and Notes

Note:Internet Explorer will ignore the generated whitespace text nodes 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 first 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 the examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().

The following code snippet can be obtained from the previous sibling node of the <author> element in the XML document:

//check if the previous sibling node is an element node
function get_previoussibling(n)
{
var x=n.previousSibling;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("author")[0];
document.write(x.nodeName);
document.write(" = ");
document.write(x.childNodes[0].nodeValue);
var y=get_previoussibling(x);
document.write("<br />Previous sibling: ");
document.write(y.nodeName);
document.write(" = ");
document.write(y.childNodes[0].nodeValue);

Output:

author = Giada De Laurentiis
Previous sibling: title = Everyday Italian

Node object reference manual