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 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 first 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 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 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 />");
  } 
}

L'output del codice sopra:

title = Everyday Italian
author = Giada De Laurentiis
year = 2005
price = 30.00