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 ignores the generated whitespace text nodes between nodes (such as newline characters), while Mozilla does not. Therefore, in the following examples, we use a function to detect the node type of the last child node.

The node type of the element node is 1, so if the first child node is not an element node, move to the next node and check if the node 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 on the differences between IE and Mozilla browsers, please visit the XML DOM tutorial on CodeW3C.com DOM Browser This section.

Example

In all examples, we will use the XML file books.xml, and 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)
  { 
  //Tumia mawingu ya mwanafunzi tu
  document.write(lastNode.childNodes[i].nodeName);
  document.write(" = ");
  document.write(lastNode.childNodes[i].childNodes[0].nodeValue);
  document.write("<br />");
  } 
}

Matokeo wa kifaa kilichotumika:

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