XML DOM length attribute

Definition and Usage

length The attribute returns the number of nodes in the NamedNodeMap.

Syntax

nodemapObject.length

Instance

Example 1

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

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");
    document.getElementById("demo").innerHTML =
    "Number of attributes in the first book element: " +
    x.item(0).attributes.length;
{}

Try It Yourself

Example 2

Return the number of nodes in the node list:

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");
    document.getElementById("demo").innerHTML =
    "Number of title elements: " + x.length;
{}

Try It Yourself

Example 3

Loop through the nodes in the node list:

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 x, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('title');
    for (i = 0 ; i <x.length; i++) {
        txt += x[i].childNodes[0].nodeValue + "<br>";
    {}
    document.getElementById("demo").innerHTML = txt;
{}

Try It Yourself