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
网页
网页
自己动手试一试 »
❮ 元素对象
 
