XML DOM previousSibling property

Definition and Usage

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

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

Syntax

elementNode.previousSibling
Tips and Notes

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

Node type of element node is 1, therefore if the previous sibling node is not an element node, move to the previous 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. In this way, the result is correct in all browsers.

Petunjuk:Untuk mendapatkan informasi lebih lanjut tentang perbedaan antara browser, kunjungi bagian DOM Browser di tutorial XML DOM.

Contoh

Contoh 1

Kode di bawah ini akan memuat "books.xml" ke xmlDoc dan mendapatkan node kembar sebelumnya dari elemen <author> pertama:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
// Memeriksa apakah node sebelumnya adalah node elemen
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>Node kembar sebelumnya: " + y.nodeName + " = " +
    y.childNodes[0].nodeValue;
}

亲自试一试

Contoh 2

Menggunakan nextSibling, mendapatkan node kemudian yang sama tingkatan:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
// Memeriksa apakah node kemudian adalah node elemen
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;
}

亲自试一试