XML DOM firstChildProperty


Element object

Definition and Usage

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

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

Syntax

elementNode.firstChild

Tips and notes

Note:Firefox and most other browsers treat empty spaces or line breaks generated between nodes as text nodes, while Internet Explorer ignores blank 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 of an element node is 1, so if the first child node is not an element node, it moves to the next node, and then continues to check whether this node is an element node. The entire process continues until the first element child node is found. By using this method, we can get correct results in all browsers.

Tip:To learn more about browser differences, please access our in our XML DOM tutorial.DOM browserChapter.


Example

The following code snippet usesloadXMLDoc()put "books.xmlLoad into xmlDoc, and get 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 elements and values 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

Try it Yourself »

Element objectother extensions