XML DOM setAttribute() Method
Element Object
Definition and Usage
The setAttribute() method adds a new attribute.
If an attribute with the specified name already exists in the element, its value is changed to the value of the value parameter.
Syntax
elementNode.setAttribute(name,value)
| Parameters | Description |
|---|---|
| name | Required. Specifies the name of the attribute to set. |
| value | Required. Specifies the value of the attribute to set. |
Example
The following code snippet uses loadXMLDoc() to load "books.xml" into xmlDoc, and add the "edition" attribute to all
Example
xmlDoc
=
loadXMLDoc
(
"
books.xml
"
)
;
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
++
)
{
document
.
write
(
x
[
i
]
.
childNodes
[
0
]
.
nodeValue
)
;
document
.
write
(
"
- Edition:
"
)
;
document
.
write
(
x
[
i
]
.
getAttribute
(
'
edition
'
)
)
;
document
.
write
(
"
"
)
;
}
Output:
Everyday Italian - Edition: FIRST
Harry Potter - Edition: FIRST
XQuery Kick Start - Edition: FIRST
Learning XML - Edition: FIRST
Try it »
Try it
setAttribute() - Change the value of an attribute
Element Object