XML DOM previousSiblingProperty


Element object

Definition and Usage

The previousSibling property returns the previous sibling node of the selected element (the node at the same tree hierarchy level that precedes it).

If no such node exists, the property returns NULL.

Syntax

elementNode.previousSibling

Tips and notes

Note:Firefox and most other browsers treat empty spaces or line breaks generated between nodes as text nodes, while Internet Explorer ignores whitespace text nodes generated between nodes. Therefore, in the example below, we will use a function to check the node type of the previous sibling node.

The node type of an element node is 1, so if the previous sibling node is not an element node, it will move to the previous node and continue checking whether this node is an element node. This process will continue until the previous sibling element node is found. In this way, we can get correct results in all browsers.

Tip:To learn more about browser differences, please visit ourDOM browserChapter.


Example

The following code snippet usesloadXMLDoc()put "books.xmlLoad xmlDoc, and get the previous sibling node from the first <author> element:

Example

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

The code above will output:

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

Try it Yourself »

Try it Yourself

nextSibling - Get the node's next sibling node


Element objectother extensions