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 will ignore the generated whitespace text nodes 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.xml, and 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;
  }
kutumia 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 />Mwana wa kina kikuu: ");
document.write(y.nodeName);
document.write(" = ");
document.write(y.childNodes[0].nodeValue);

Matokeo wa maktaba wa juu:

author = Giada De Laurentiis
Mwana wa kina kikuu: title = Everyday Italian