XML DOM attribute 屬性

定義和用法

attribute 屬性返回 NamedNodeMap(屬性列表),其中包含所選節點的屬性。

如果所選節點不是元素,則此屬性返回 NULL。

提示:此屬性僅適用于元素節點。

語法

elementNode.attributes

實例

下面的代碼將 "books.xml" 加載到 xmlDoc 中,并獲取 "books.xml" 中第一個 <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("book")[0].attributes;
    document.getElementById("demo").innerHTML =
    x.length;
}

親自試一試

實例

2 下面的代碼將 "books.xml" 加載到 xmlDoc 中,并獲取第一個 <book> 元素中 "category" 屬性的值:
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, att, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book');
    for (i = 0; i < x.length; i++) {
        att = x.item(i).attributes.getNamedItem("category");
        txt += att.value + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

親自試一試