Latest web development tutorials

XML DOM previousSibling property

Element Object Reference Element object

Definition and Usage

previousSibling property returns the previous sibling node selected element (the next node in the same tree hierarchy).

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

grammar

elementNode.previousSibling

Tips and Notes

Note: Firefox and most other browsers, the empty spaces between the nodes will generate or wrap as text nodes, while Internet Explorer will ignore whitespace text nodes between nodes generated.Thus, in the example below, we'll use a function that checks the node type of a sibling node.

Node type element node is 1, so if the previous sibling node is not an element node, it will move to the previous node, and checks if this node is an element node. The whole process continues until the previous sibling element node is found. Through this method, we can get the right results in all browsers.

Tip: For more information about browser differences, please visit us in our XML DOM tutorial DOM browser section.


Examples

The following code fragment uses loadXMLDoc () to " the Books.xml " into xmlDoc, and get on a sibling nodes from the first <author> element:

Examples

//check if the previous sibling node is 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("
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"

Try Demos

get the next sibling node node - nextSibling


Element Object Reference Element object