XML DOM length 屬性

定義和用法

length 屬性返回 NamedNodeMap 中的節點數。

語法

nodemapObject.length

實例

例子 1

下面的代碼將 "books.xml" 加載到 xmlDoc 中,并獲取第一個 <book> 元素中的屬性數量:

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

親自試一試

例子 2

返回節點列表中的節點數:

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

親自試一試

例子 3

循環遍歷節點列表中的節點:

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

親自試一試