XML DOM firstChild attribute

Dokumentobjektets referenshandbok

Definition and usage

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

Syntax:

documentObject.firstChild 

Tips and comments

Note:Internet Explorer will ignore the whitespace text nodes generated 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.

Element nodes have a node type of 1, so if the first child node is not an element node, it will move to the next node and continue checking whether this node is an element node. This process will continue until the first element child node is found. With this method, we can get the correct result in Internet Explorer and Mozilla.

Tips:För mer information om skillnaderna mellan IE och Mozillas XML DOM, besök vår DOM-webbläsare kapitel.

exempel

I alla exempel kommer vi att använda XML-filer books.xmloch JavaScript-funktioner loadXMLDoc()

Följande kodsnutt kan visa dokumentets första barnnodens nodnamn och nodtyp:

//Kontrollera om den första noden är en elementnod
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 + ")");

Utttag:

Nodename: bookstore (nodetype: 1)

Dokumentobjektets referenshandbok