XML DOM lastChild
Property
Definition and Usage
The lastChild
property returns the last child node of the document.
Syntax
Tips and Notes
Note: Firefox and most other browsers treat empty spaces or line breaks between nodes as text nodes, whereas Internet Explorer ignores empty text nodes generated between nodes. Therefore, in the example below, we will use a function to check the node type of the last child node.
The node type for element nodes is 1. So, if the last child node is not an element node, it moves to the previous node and continues checking if this node is an element node. This process continues until the last element child node is found. By using this method, we can get the correct result in all browsers.
Tip: For more information on browser differences, visit our DOM Browsers section in our XML DOM tutorial.
Example
The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc
and retrieves the last child node of the document:
Example
// Get the name and value of the last child 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 + ")<br>");
Output:
Try It
Get the first child node of the document