XML DOM childNodes Property


❮ Element Object

Example 1

The following code fragment loads "books.xml" into xmlDoc and gets the text node from the first <title> element in "books.xml":

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("title")[0];
    var y = x.childNodes[0];
    document.getElementById("demo").innerHTML =
    y.nodeValue;
}

The output of the code above will be:

Everyday Italian
Try it Yourself »

Definition and Usage

The childNodes property returns a NodeList containing the child nodes of the selected node

If the selected node has no children, this property returns a NodeList containing no nodes.

Syntax

elementNode.childNodes

Tips and Notes

Tip: To loop through a childNodes list, it is more efficient to use the nextSibling property than to explicitly use the childNodes list of the parent object.


Example

The following code fragment loads "books.xml" into xmlDoc and gets the number of child nodes from the first <book> element in "books.xml":

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("book")[0].childNodes;
    document.getElementById("demo").innerHTML =
    x.length;
}

The output of the code above will be:

9

In IE9 and earlier, the output of the code above will be:

4
Try it Yourself »

Firefox, and most other browsers, will treat empty white-spaces or new lines as text nodes, Internet Explorer will not. So, in the example above, the output will be different.

To read more about the differences between browsers, visit our DOM Browsers chapter in our XML DOM Tutorial.


❮ Element Object
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.