XML DOM setAttribute() Method
Definition and Usage
The setAttribute() method creates or changes a new attribute.
Syntax:
elementNode.setAttribute(name,value)
Parameters | Description |
---|---|
name | Required. Specifies the attribute name to be set. |
value | Required. Specifies the attribute value to be set. |
Description
This method sets the specified attribute to the specified value. If there is no attribute with the specified name, this method will create a new attribute.
Example
In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
The following code snippet adds an "edition" attribute to all <book> elements in "books.xml":
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
x.item(i).setAttribute("edition","first");
}
//Output book title and edition value
x=xmlDoc.getElementsByTagName("title");
for (i=0;i<x.length;i++)
{
document.write(x[i].childNodes[0].nodeValue);
document.write(" - Edition: ");
document.write(x[i].parentNode.getAttribute('edition'));
document.write("<br />");
}
Output:
Everyday Italian - Edition: FIRST Harry Potter - Edition: FIRST XQuery Kick Start - Edition: FIRST Learning XML - Edition: FIRST