XML DOM attributes Property
❮ 元素物件
示例 1
以下程式碼片段將 "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;
}
上面程式碼的輸出將是
1
自己動手試一試 »
定義和用法
attributes 屬性返回一個 NamedNodeMap(屬性列表),其中包含所選節點的屬性。
如果所選節點不是元素,則此屬性返回 NULL。
語法
elementNode.attributes
提示和註釋
提示:此屬性僅對元素節點有效。
示例 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;
}
上面程式碼的輸出將是
cooking
children
網頁
網頁
自己動手試一試 »
❮ 元素物件