XML DOM lastChild
Property
Definition and Usage
The lastChild
property returns the last child node of the specified node.
Syntax
Tips and Notes
Note: Firefox and most other browsers treat empty spaces or line breaks between nodes as text nodes, while Internet Explorer ignores empty text nodes generated between nodes. Therefore, in the following example, we will use a function to check the node type of the last child node.
The node type of an element node is 1, so if the last child node is not an element node, it will move to the previous node and continue checking if this node is an element node. This process will continue until the last element child node is found. This method ensures correct results across all browsers.
Tip: For more information on browser differences, visit our DOM Browsers section in the XML DOM tutorial.
Example
The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc
and displays the node name and node type of the document's last child node:
Example
// Get the last child node name and value
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("Node name: " + x.nodeName);
document.write(" (node type: " + x.nodeType + ")<br>");
Output:
Node name: bookstore (node type: 1)
Try It Demos
Get the first child node of the document