XML DOM previousSibling property

Definition and usage

The previousSibling property returns the previous sibling node of the selected node (the previous node at the same tree level).

If such a node does not exist, this property returns null.

Syntax:

elementNode.previousSibling

Tips and comments

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 detect the node type of the previous sibling node.

The node type of the element node is 1, so if the previous sibling node is not an element node, move to the previous node and check if the node is an element node. This process continues until the previous sibling node is found. This method ensures that the correct results are 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 this section.

example

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

the following code snippet retrieves the previous sibling node of the first <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);

Η έξοδος του παραπάνω κώδικα:

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