Proprietà lastChild dell'XML DOM
Definizione e uso
lastChild
L'attributo restituisce l'ultimo figlio del documento.
Sintassi
documentObject.lastChild
Attenzione:Firefox e la maggior parte degli altri browser considerano gli spazi bianchi o i righi di ritorno come nodi di testo, mentre Internet Explorer non lo fa. Pertanto, nell'esempio seguente, utilizziamo una funzione per controllare il tipo di nodo dell'ultimo figlio.
Il nodeType degli elementi è 1, quindi se l'ultimo figlio non è un nodo elemento, si sposta al nodo precedente e si verifica se questo nodo è un nodo elemento. Questo processo continua fino a trovare l'ultimo figlio (deve essere un nodo elemento). In questo modo, i risultati sono corretti in tutti i browser.
Suggerimento:Per ulteriori informazioni sulle differenze tra i browser, visitare la sezione DOM Browser dell'insegnamento XML DOM.
Esempio
Esempio 1
Il codice seguente carica "books.xml" in xmlDoc e mostra il nome e il tipo del ultimo figlio del documento:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Controllare se l'ultimo nodo è un nodo elemento function get_lastchild(n) { var x = n.lastChild; while (x.nodeType != 1) { x = x.previousSibling; } return x; } function myFunction(xml) { var xmlDoc = xml.responseXML; var x = get_lastchild(xmlDoc); document.getElementById("demo").innerHTML = "Nodename: " + x.nodeName + " (nodetype: " + x.nodeType + ")<br>"; }
Esempio 2
Ottenere il primo figlio del documento:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); // Controllare se il primo nodo è un nodo elemento function get_firstchild(n) { var x = n.firstChild; while (x.nodeType != 1) { x = x.nextSibling; } return x; } function myFunction(xml) { var xmlDoc = xml.responseXML; // Ottenere il primo figlio del documento var x = get_firstchild(xmlDoc); // Ottenere il primo figlio dell'elemento radice var y = get_firstchild(xmlDoc.documentElement); document.getElementById("demo").innerHTML = "Nodename: " + x.nodeName + " (nodetype: " + x.nodeType + ")<br>" + "Nodename: " + y.nodeName + " (nodetype: " + y.nodeType + ")<br>"; }