Easy Tutorial
❮ Dom Prop Node Nextsibling Met Element Getattributenodens ❯

XML DOM firstChild Property



Definition and Usage

The firstChild property returns the first child node of the selected element.

If the selected node has no child nodes, this property returns NULL.

Syntax


Tips and Notes

Note: Firefox and most other browsers will treat spaces or newlines between nodes as text nodes, while Internet Explorer will ignore whitespace text nodes generated between nodes. Therefore, in the following example, we will use a function to check the node type of the first child node.

The node type for an element node is 1. So, if the first child node is not an element node, it will move to the next node and continue checking if it is an element node. This process will continue until the first element child node is found. By using this method, we can get the correct result in all browsers.

Tip: For more information about browser differences, visit our DOM Browsers section in our XML DOM tutorial.


Example

The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc and retrieves the first child node:

Example

// Get the first child node
function get_firstchild(n)
{
  x = n.firstChild;
  while (x.nodeType != 1)
  {
    x = x.nextSibling;
  }
  return x;
}

xmlDoc = loadXMLDoc("books.xml");

x = xmlDoc.documentElement;
firstNode = get_firstchild(x);

for (i = 0; i < firstNode.childNodes.length; i++)
{ 
  if (firstNode.childNodes[i].nodeType == 1)
  { 
    // Output node element and value
    document.write(firstNode.childNodes[i].nodeName);
    document.write(" = ");
    document.write(firstNode.childNodes[i].childNodes[0].nodeValue);
    document.write("<br>");
  } 
}

The above code will output:

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

❮ Dom Prop Node Nextsibling Met Element Getattributenodens ❯