Proprietà length dell'XML DOM

Definizione e uso

length L'attributo restituisce il numero di nodi nella lista di nodi.

Sintassi

nodelistObject.length

Esempio

Esempio 1

Il codice seguente carica "books.xml" nel xmlDoc e ottiene il numero di elementi <title>:

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 =
    "Numero di elementi di title: " + x.length;
{}

Prova tu stesso

Esempio 2

Eseguire un ciclo per esplorare i nodi nella lista di nodi:

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;
{}

Prova tu stesso