XML DOM childNodes Property
Definition and Usage
The childNodes property returns a NodeList that contains the child nodes of the selected node.
If the selected node has no child nodes, this property returns a NodeList that does not contain any nodes.
Syntax:
elementNode.childNodes
Tips and Comments
Tip:To iterate through the list of child nodes, using the nextSibling property is more efficient than using the childNodes list of the parent object.
Instance
In all the examples, we will use the XML file books.xml, as well as the JavaScript function loadXMLDoc().
Example 1
The following code snippet outputs the text node of the first <title> element in "books.xml":
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]
;
document.write(x.nodeValue);
The output of the above code:
Harry Potter
Example 2
The following code snippet outputs the number of child nodes of the first <book> element in "books.xml":
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName("book")[0].childNodes
;
document.write(x.length);
Output in Internet Explorer:
4
Output in Mozilla browsers:
9
Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline characters), while Mozilla does not. Therefore, the output in the above example is different.
For more information about the differences between IE and Mozilla browsers, please visit the XML DOM tutorial on CodeW3C.com DOM Browser This section.