XML DOM lastChild Attribute

Definition and Usage

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

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

Syntax:

elementNode.lastChild

Tips and Comments

Note:Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline characters), while Mozilla does not. Therefore, in the following example, we use a function to detect the node type of the last child node.

The node type of an element node is 1, so if the first child node is not an element node, move to the next node and check if it is an element node. This process continues until the first child node is found. This method ensures that the correct results are obtained in both Internet Explorer and Mozilla.

For more information about the differences between IE and Mozilla browsers, please visit the XML DOM tutorial on CodeW3C.com. DOM Browser This section.

Example

In all the examples, we will use the XML file books.xml, as well as the JavaScript function loadXMLDoc().

The following code snippet retrieves the last child from "books.xml":

//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("books.xml");
var x=xmlDoc.documentElement;
var lastNode=get_lastchild(x);
for (var i=0;i<lastNode.childNodes.length;i++)
{ 
if (lastNode.childNodes[i].nodeType==1)
  { 
  //Process only element nodes
  document.write(lastNode.childNodes[i].nodeName);
  document.write(" = ");
  document.write(lastNode.childNodes[i].childNodes[0].nodeValue);
  document.write("<br />");
  } 
}

The output of the above code is:

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