XML DOM firstChild attribute

Node object reference manual

Definition and usage

The firstChild attribute can return the first child node of the specified node.

Syntax:

nodeObject.firstChild

Tips and notes

Note:Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following example, 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 on the differences between XML DOM in IE and Mozilla browsers, please visit our DOM browser Chapter.

Example

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

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

Output:

Nodename: bookstore (nodetype: 1)

Node object reference manual