Easy Tutorial
❮ Prop Element Lastchild Dom Met Element Setattribute ❯

XML DOM previousSibling Property



Definition and Usage

The previousSibling property returns the previous sibling node of the selected element (the next node 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 newlines 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 for an element node is 1. Thus, if the previous sibling node is not an element node, it will move to the previous 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 our XML DOM tutorial.


Example

The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc and retrieves the previous sibling node from the first <author> element:

Example

// Get the previous sibling node of the 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


❮ Prop Element Lastchild Dom Met Element Setattribute ❯