XML DOM lastChild Property
Definition and Usage
The lastChild property can return the last child node of the document.
Syntax:
documentObject.lastChild
Tips and Notes
Note:Internet Explorer will ignore the whitespace text nodes generated between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following example, we will use a function to check the node type of the first child node.
The node type of an element node is 1, so if the first child node is not an element node, it will move to the next node and continue to check whether this node is an element node. This process will continue until the first element child node is found. In this way, we can get the correct result in Internet Explorer and Mozilla.
Tip:For more information about the differences between XML DOM in IE and Mozilla browsers, please visit our DOM browser Chapter.
Example
In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
The following code snippet can display the node name and node type of the last child node of the document:
//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;
}
xmlDoc=loadXMLDoc("/example/xdom/books.xml");
var x=get_lastchild(xmlDoc);
document.write("Nodename: " + x.nodeName);
document.write(" (nodetype: " + x.nodeType + ")");
Output:
Nodename: bookstore (nodetype: 1)