XML DOM nextSibling Property

Node Object Reference Manual

Definition and Usage

The nextSibling property can return the element immediately following an element (at the same tree level).

If there is no such node, the property returns null.

Syntax:

nodeObject.nextSibling

Tips and Notes

Note:Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following examples, we will use a function to check the node type of the first child node.

The node type of an element node is 1, so if the first child node is not an element node, it will move to the next node and continue to check whether this node is an element node. This process will continue until the first element child node is found. Through this method, we can get the correct method in Internet Explorer and Mozilla.

Tip:For more information on the differences between XML DOM in IE and Mozilla browsers, please visit our DOM Browser Chapter.

Example

In all the examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().

The following code snippet can obtain the next sibling node of the first <title> element in the XML document:

//check if the next sibling node is an element node
function get_nextsibling(n)
  {
  var x=n.nextSibling;
  while (x.nodeType!=1)
   {
   x=x.nextSibling;
   }
  return x;
  }
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("title")[0];
document.write(x.nodeName);
document.write(" = ");
document.write(x.childNodes[0].nodeValue);
var y=get_nextsibling(x);
document.write("<br />Next sibling: ");
document.write(y.nodeName);
document.write(" = ");
document.write(y.childNodes[0].nodeValue);

Output:

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

Node Object Reference Manual