XML DOM attribute 属性

定義と使用法

attribute 属性は NamedNodeMap(属性リスト)を返し、選択されたノードの属性を含みます。

選択されたノードが要素でない場合、この属性は NULL を返します。

ヒント:この属性は要素ノードにのみ適用されます。

構文

elementNode.attributes

以下のコードは "books.xml" を xmlDoc に読み込み、最初の <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;
}

自分で試してみる