Easy Tutorial
❮ Prop Attr Ownerdocument Dom Met Document Createcomment ❯

XML DOM firstChild Property



Definition and Usage

The firstChild property returns the first child node of the document.

Syntax


Tips and Notes

Note: Firefox and most other browsers will treat spaces or newlines between nodes as text nodes, whereas 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. Thus, 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 achieve consistent results across all browsers.

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


Example

The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc and displays the node name and node type of the document's first child node:

Example

// Get the name and value of 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 = get_firstchild(xmlDoc);
document.write("Nodename: " + x.nodeName);
document.write(" nodetype: " + x.nodeType + "<br>");

Output:

Nodename: bookstore (nodetype: 1)

Try It

Get the last child node of the document


❮ Prop Attr Ownerdocument Dom Met Document Createcomment ❯