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 ignores 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 first child node.
The node type of an element node is 1, so if the first child 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 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 examples, we will use the XML file books.xml, as well as the JavaScript function loadXMLDoc().
the following code snippet retrieves the first child 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)
{
//Επεξεργασία μόνο αντικειμένων κόμβων
document.write(firstNode.childNodes[i].nodeName);
document.write(" = ");
document.write(firstNode.childNodes[i].childNodes[0].nodeValue);
document.write("<br />");
}
}
Η έξοδος του παραπάνω κώδικα:
title = Everyday Italian author = Giada De Laurentiis year = 2005 price = 30.00