XML DOM firstChild property

Document object reference manual

Definition and usage

The firstChild property can return the first child node of the document.

Syntax:

documentObject.firstChild 

Tips and comments

Note:Internet Explorer will ignore the blank text nodes generated between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following examples, we will use a function to check the node type of the first child node.

The node type of 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 to check whether this node is an element node. This process will continue until the first element child node is found. In this way, we can get the correct result in Internet Explorer and Mozilla.

Tip:For more information about the differences between XML DOM in IE and Mozilla browsers, please visit our DOM browser Chapter.

Instance

In all examples, we will use the XML file books.xml, as well as the JavaScript function loadXMLDoc().

The following code snippet can display the node name and node type of the first child node of the document:

//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("/example/xdom/books.xml");
var x=get_firstchild(xmlDoc);
document.write("Nodename: " + x.nodeName);
document.write(" (nodetype: " + x.nodeType + ")");

Output:

Nodename: bookstore (nodetype: 1)

Document object reference manual