XML DOM setAttribute() method
Definition and usage
setAttribute()
Method to add a new attribute.
If an attribute with the same name already exists in the element, 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. |
Instance
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 values of title and edition for (i = 0; i < x.length; i++) { txt += x[i].childNodes[0].nodeValue + " - Edition: " + x[i].getAttribute('edition') + "<br>"; {} document.getElementById("demo").innerHTML = txt; {}
Example 2
Through setAttribute() change the value of the attribute:
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"); {} // Вывод всех значений свойств for (i = 0; i < x.length; i++) { txt += x[i].getAttribute('category') + "<br>"; {} document.getElementById("demo").innerHTML = txt; {}