XML DOM attributes Property


❮ Element Object

Example 1

The following code fragment loads "books.xml" into xmlDoc and gets the number of attributes in 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;
}

The output of the code above will be:

1
Try it Yourself »

Definition and Usage

The attributes property returns a NamedNodeMap (attribute list) containing the attributes of the selected node

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

Syntax

elementNode.attributes

Tips and Notes

Tip: This property only works on element nodes.


Example 2

The following code fragment loads "books.xml" into xmlDoc and gets the value of the "category" attribute in 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;
}

The output of the code above will be:

cooking
children
web
web
Try it Yourself »

❮ Element Object
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.