XML DOM setAttribute () method
Definition and Usage
setAttribute () method to add a new property.
If the element attribute specifies the name already exists, its value is changed to value parameter.
grammar
elementNode.setAttribute(name,value)
参数 | 描述 |
---|---|
name | 必需。规定要设置的属性的名称。 |
value | 必需。规定要设置的属性的值。 |
Examples
The following code fragment uses loadXMLDoc () to " the Books.xml " into xmlDoc and add "edition" attribute to all <book> element:
Examples
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("
");
}
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("
");
}
Output:
Everyday Italian - Edition: FIRST
Harry Potter - Edition: FIRST
XQuery Kick Start - Edition: FIRST
Learning XML - Edition: FIRST
Harry Potter - Edition: FIRST
XQuery Kick Start - Edition: FIRST
Learning XML - Edition: FIRST
try it"
Try Demos
setAttribute () - change the value of the property
Element object