XML DOM previousSibling property

Definition and Usage

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

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

Syntax

nodeObject.previousSibling
Tips and Notes

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

Element nodes' nodeType is 1, so if the previous sibling node is not an element node, move to the next node and check if the node is an element node. This will continue until the previous sibling node (must be an element node) is found. As a result, it is correct in all browsers.

提示:如需了解有关浏览器之间差异的更多信息,请访问 XML DOM 教程中的 DOM 浏览器章节。

Eksempel

Eksempel 1

下面的代码将 "books.xml" 加载到 xmlDoc 中,并从第一个 <author> 元素获取前一个同级节点:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
// 检查前一个同级节点是否是元素节点
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;
}

Prøv det selv

Eksempel 2

获取节点的下一个同级节点:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
// 检查下一个同级节点是否是元素节点
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>Næste bror: " + y.nodeName + " = " + 
    y.childNodes[0].nodeValue;
}

Prøv det selv