Latest web development tutorials

XML DOM firstChild property

Element Object Reference Element object

Definition and Usage

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

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

grammar

elementNode.firstChild

Tips and Notes

Note: Firefox and most other browsers, the empty spaces between the nodes will generate or wrap as text nodes, while Internet Explorer will ignore whitespace text nodes between nodes generated.Thus, in the example below, we'll use a function that checks the node type of the first child node.

Node type element node is 1, so if the first child node is not an element node, it will move to the next node, and checks if this node is an element node. The whole process will continue until the first element child node is found. Through this method, we can get the right results in all browsers.

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


Examples

The following code fragment uses loadXMLDoc () to " the Books.xml " into xmlDoc, and made the first child node:

Examples

//check if the first node is an element 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)
{
//Process only element nodes
document.write(firstNode.childNodes[i].nodeName);
document.write(" = ");
document.write(firstNode.childNodes[i].childNodes[0].nodeValue);
document.write("
");
}
}

The code above will output:

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

try it"

Element Object Reference Element object