XML DOM firstChild Property
Definition and Usage
The firstChild property returns the first child node of the selected node.
If the selected node has no child nodes, this property returns NULL.
Syntax:
elementNode.firstChild
Tips and Comments
Note:Internet Explorer will ignore the whitespace text nodes generated 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 first 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 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 about the differences between IE and Mozilla browsers, please visit the XML DOM tutorial on CodeW3C.com. DOM Browser in 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 first child node from "books.xml":
//check if the first node is an element node
function get_firstchild(n)
{
var x =n.firstChild
;
while (x.nodeType != 1)
{
x=x.nextSibling;
}
return x;
}
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.documentElement;
var firstNode=get_firstchild(x);
for (var i=0;i<firstNode.childNodes.length;i++)
{
if (firstNode.childNodes[i].nodeType==1)
{
//Process only element nodes
document.write(firstNode.childNodes[i].nodeName);
document.write(" = ");
document.write(firstNode.childNodes[i].childNodes[0].nodeValue);
document.write("<br />");
}
}
The output of the above code is:
title = Everyday Italian author = Giada De Laurentiis year = 2005 price = 30.00