Proprietà previousSibling del XML DOM

Definizione e utilizzo

previousSibling La proprietà restituisce il nodo immediatamente precedente (il nodo successivo nello stesso livello dell'albero).

Se non esiste tale nodo, questa proprietà restituisce null.

Sintassi

nodeObject.previousSibling
Suggerimenti e Note

Attenzione:Firefox e la maggior parte degli altri browser considerano gli spazi o le virgole di riga come nodi di testo, mentre Internet Explorer non lo fa. Nei seguenti esempi, utilizziamo una funzione per verificare il tipo di nodo del nodo同级 precedente.

Il nodeType dell'elemento è 1, quindi se il nodo同级 precedente non è un nodo elemento, si sposta al nodo successivo e si verifica se il nodo è un nodo elemento. Questo continuerà fino a trovare il nodo同级 precedente (deve essere un nodo elemento). In questo modo, il risultato è corretto in tutti i browser.

Suggerimento:Per ulteriori informazioni sulle differenze tra i browser, visitare la sezione DOM Browser dell'iniziozione XML DOM.

Esempio

Esempio 1

The following code loads "books.xml" into xmlDoc and gets the previous sibling node of the first <author> 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 previous sibling node 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>Precedente fratello: " + y.nodeName + " = " +
    y.childNodes[0].nodeValue;
}

Prova personalmente

Esempio 2

Get the next sibling node of the 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 node 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>Successore: " + y.nodeName + " = " + 
    y.childNodes[0].nodeValue;
}

Prova personalmente