Easy Tutorial
❮ Prop Comment Length Met Element Issamenode ❯

XML DOM previousSibling Property



Definition and Usage

The previousSibling property returns the node immediately preceding the element (at the same tree level).

If no such node exists, this property returns null.

Syntax


Tips and Notes

Note: Firefox and most other browsers will treat blank spaces or new lines between nodes as text nodes, whereas Internet Explorer will ignore blank text nodes generated between nodes. Therefore, in the following example, we will use a function to check the node type of the previous sibling node.

The node type of an element node is 1. Thus, if the previous sibling node is not an element node, it will move to the next node and continue checking if this node is an element node. This process will continue until the previous sibling element node is found. By using this method, we can achieve consistent results across all browsers.

Tip: For more information on browser differences, please visit our DOM Browsers section in the XML DOM tutorial.


Example

The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc and retrieves the previous sibling node of 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 above code will output:

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

Try It Out

nextSibling - Get the next sibling node of an element node


❮ Prop Comment Length Met Element Issamenode ❯