Easy Tutorial
❮ Dom Met Element Removeattribute Prop Element Previoussibling ❯

XML DOM lastChild Property



Definition and Usage

The lastChild property returns the last child node of the selected element.

If the selected node has no child nodes, this property returns NULL.

Syntax


Tips and Notes

Note: Firefox and most other browsers treat empty spaces or newlines 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 for an element node is 1. Thus, if the first child node is not an element node, it moves to the next node and continues checking if it is an element node. This process continues until the first 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 retrieves the last child node:

Example

// Get 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 = xmlDoc.documentElement;
lastNode = get_lastchild(x);

for (i = 0; i < lastNode.childNodes.length; i++) {
  if (lastNode.childNodes[i].nodeType == 1) {
    // Output element node and value
    document.write(lastNode.childNodes[i].nodeName);
    document.write(" = ");
    document.write(lastNode.childNodes[i].childNodes[0].nodeValue);
    document.write("<br>");
  }
}

The above code will output:

title = Learning XML
author = Erik T. Ray
year = 2003
price = 39.95

❮ Dom Met Element Removeattribute Prop Element Previoussibling ❯