XML DOM ιδιότητα lastChild

Ορισμός και Χρήση

lastChild Η ιδιότητα επιστρέφει τον τελευταίο υποκόμβο του έγγραφου.

Γραμματική

documentObject.lastChild
Συμβουλές και Σημειώσεις

Σημείωση:Firefox και πολλοί άλλοι περιηγητές θεωρούν το κενό ή τη μεταβίβαση γραμμής ως κόμβο κειμένου, ενώ ο Internet Explorer δεν το κάνει. Επομένως, στον παρακάτω παράδειγμα, χρησιμοποιούμε μια συνάρτηση για να ελέγξουμε τον τύπο του τελευταίου υποκόμβου.

The nodeType of element nodes is 1, so if the last child node is not an element node, it will move to the previous node and check if that node is an element node. This will continue until the last child node (which must be an element node) is found. This ensures that the result is correct in all browsers.

Hint: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 displays the name and type of the last child node of the document:

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 last node is an element node
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>"
}

亲自试一试

Example 2

Γained the first child of the document:

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 first node is an element node
function get_firstchild(n) {
    var x = n.firstChild;
    while (x.nodeType != 1) {
        x = x.nextSibling;
    }
    return x;
}
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    // Γained the first child of the document
    var x = get_firstchild(xmlDoc);
    // Γained the first child of the root element
    var y = get_firstchild(xmlDoc.documentElement);
    document.getElementById("demo").innerHTML =
    "Nodename: " + x.nodeName +" 
    " (nodetype: " + x.nodeType + ")<br>" +
    "Nodename: " + y.nodeName + 
    " (nodetype: " + y.nodeType + ")<br>";
}

亲自试一试