XML DOM attribute property

Definition and Usage

attribute This property returns a NamedNodeMap (attribute list) that contains the attributes of the selected node.

If the selected node is not an element, this property returns NULL.

Tip:This property is only applicable to element nodes.

Syntax

elementNode.attributes

Example

The following code loads "books.xml" into xmlDoc and retrieves the number of attributes of the first <title> element in "books.xml":

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

Try It Yourself

Example

2 The following code loads "books.xml" into xmlDoc and retrieves the value of the "category" attribute from the first <book> element:
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;
}

Try It Yourself