XML DOM lastChild-Eigenschaft

Definition und Verwendung

lastChild Die Eigenschaft gibt den letzten Kindknoten des angegebenen Knotens zurück.

Syntax

nodeObject.lastChild
Tips and Notes

Hinweis:Firefox und die meisten anderen Browser betrachten Leerzeichen oder Zeilenumbrüche als Textknoten, während Internet Explorer dies nicht tut. Daher verwenden wir in den folgenden Beispielen eine Funktion, um den Knotentyp des letzten Kindknotens zu überprüfen.

Element nodes have a nodeType of 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.

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

实例

例子 1

下面的代码将 "books.xml" 加载到 xmlDoc 中,并显示文档最后一个子节点的节点名称:

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_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>";
}

Try It Yourself

例子 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_firstchild(n) {
    var x = n.firstChild;
    while (x.nodeType != 1) {
        x = x.nextSibling;
    }
    return x;
}
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    // 获取文档的第一个子节点
    var x = get_firstchild(xmlDoc);
    // 获取根元素的第一个子节点
    var y = get_firstchild(xmlDoc.documentElement);
    document.getElementById("demo").innerHTML =
    "Nodename: " + x.nodeName +" 
    " (nodetype: " + x.nodeType + ")<br>" +
    "Nodename: " + y.nodeName + 
    " (nodetype: " + y.nodeType + ")<br>";
}

Try It Yourself