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 example, we use a function to detect the node type of the first child node.
The node type of the element node is 1, so if the first child 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 is found. This method ensures that the correct result is 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 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)
{
//Process only element nodes
document.write(firstNode.childNodes[i].nodeName);
document.write(" = ");
document.write(firstNode.childNodes[i].childNodes[0].nodeValue);
document.write("<br />");
}
}
Output na koda na dukkanin:
title = Everyday Italian author = Giada De Laurentiis year = 2005 price = 30.00