XML DOM setAttribute() Method

Definition and Usage

setAttribute() Method to add new attributes.

If the element already contains an attribute with the same name, then its value is changed to value The value of the parameter.

Syntax

elementNode.setAttribute(name,value)
Parameters Description
name Required. Specifies the name of the attribute to be set.
value Required. Specifies the value to be set for the attribute.

Example

Example 1

The following code loads "books.xml" into xmlDoc and adds the "edition" attribute to all <book> elements:

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, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('title');
    // Add a new attribute to each title element
    for (i = 0; i < x.length; i++) {
        x[i].setAttribute("edition", "first");
    }
    // Output the title and edition values
    for (i = 0; i < x.length; i++) {
        txt += x[i].childNodes[0].nodeValue +
        " - Edition: " +
        x[i].getAttribute('edition') + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

Try It Yourself

Example 2

Change the value of the attribute through setAttribute():

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, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book');
    for (i = 0; i < x.length; i++) { 
        x.item(i).setAttribute("category", "BESTSELLER");  
    }
    // Output all attribute values
    for (i = 0; i < x.length; i++) { 
        txt += x[i].getAttribute('category') + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

Try It Yourself