XML DOM nextSibling Property

Definition and Usage

nextSibling This property returns the next sibling node of the selected element (the next node at the same tree level).

If such a node does not exist, this property returns null.

Syntax

elementNode.nextSibling
Tips and Notes

Note:Firefox and most other browsers treat whitespace or newline as text nodes, while Internet Explorer does not. Therefore, in the following example, we use a function to check the node type of the next sibling node.

The nodeType of an element node is 1, so if the next sibling node is not an element node, it moves to the next node and checks whether the node is an element node. This will continue until the next sibling node (which must be an element node) is found. As a result, the output is correct in all browsers.

Tip:For more information on differences between browsers, please visit the DOM Browser section in the XML DOM tutorial.

Example

Example 1

The following code loads "books.xml" into xmlDoc and gets the next sibling from the first <title> element:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
// Check if the next sibling is an element node
function get_nextsibling(n) {
    var x = n.nextSibling;
    while (x.nodeType != 1) {
        x = x.nextSibling;
    }
    return x;
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("title")[0];
    var y = get_nextsibling(x);
    document.getElementById("demo").innerHTML = x.nodeName + " = " +
    x.childNodes[0].nodeValue +
    "<br>Next sibling: " + y.nodeName + " = " +
    y.childNodes[0].nodeValue;
}

Try It Yourself

Example 2

Use the previousSibling method to get the previous sibling of the node:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
// Check if the previous sibling is an element node
function get_previoussibling(n) {
    var x = n.previousSibling;
    while (x.nodeType != 1) {
        x = x.previousSibling;
    }
    return x;
}
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("author")[0];
    var y = get_previoussibling(x);
    document.getElementById("demo").innerHTML = x.nodeName + " = " + 
    x.childNodes[0].nodeValue +
    "<br>Previous sibling: " + y.nodeName + " = " + 
    y.childNodes[0].nodeValue;
}

Try It Yourself