lastChild 属性返回文档的最后一个子节点。
documentObject.lastChild
注释:Firefox 以及大多数其他的浏览器,会把节点间生成的空的空格或者换行当作文本节点,而 Internet Explorer 会忽略节点间生成的空白文本节点。因此,在下面的实例中,我们会使用一个函数来检查最后一个子节点的节点类型。
元素节点的节点类型是 1,因此如果最后一个子节点不是一个元素节点,它就会移至上一个节点,然后继续检查此节点是否为元素节点。整个过程会一直持续到最后一个元素子节点被找到为止。通过这个方法,我们就可以在所有的浏览器中得到正确的结果。
提示:如需了解更多有关浏览器差异的知识,请在我们的 XML DOM 教程中访问我们的 DOM 浏览器 章节。
下面的代码片段使用 loadXMLDoc() 把 "books.xml" 载入 xmlDoc 中,并取得文档的最后一个子节点:
//check if the last node is an element node
function get_lastchild(n)
{
x=n.lastChild;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}
xmlDoc=loadXMLDoc("books.xml");
x=get_lastchild(xmlDoc);
document.write("Nodename: " + x.nodeName);
document.write(" (nodetype: " + x.nodeType);
输出:
Nodename: bookstore (nodetype: 1)
取得文档的第一个子节点
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
//check if the first node is an element node
function get_firstchild(n)
{
x=n.firstChild;
while (x.nodeType!=1)
{
x=x.nextSibling;
}
return x;
}
xmlDoc=loadXMLDoc("books.xml");
x=get_firstchild(xmlDoc);
document.write("Nodename: " + x.nodeName);
document.write(" (nodetype: " + x.nodeType + ")<br>");
//Get the first child node of the root element
y=get_firstchild(xmlDoc.documentElement);
document.write("Nodename: " + y.nodeName);
document.write(" (nodetype: " + y.nodeType);
</script>
</body>
</html>