XML DOM setAttribute() Method
❮ Element Object
Example
The following code fragment loads "books.xml" into xmlDoc and adds an "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 titles
and edition value
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue +
" - Edition: " +
x[i].getAttribute('edition')
+ "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
Output:
Everyday Italian - Edition: first
Harry Potter - Edition: first
XQuery Kick Start - Edition: first
Learning XML - Edition: first
Try it Yourself »
Definition and Usage
The setAttribute() method adds a new attribute.
If an attribute with that name already exists in the element, its value is changed to be that of the value parameter
Syntax
elementNode.setAttribute(name,value)
Parameter | Description |
---|---|
name | Required. Specifies the name of the attribute to set |
value | Required. Specifies the value of the attribute to set |
Try-It-Yourself Demos
setAttribute() - Change an attribute's value
❮ Element Object