Main Page

NamedNodeMap

The
NamedNodeMap
object also has a
length
property to indicate the number of nodes it contains.
When used to represent attributes, each node in the
NamedNodeMap
is an
Attr
node, whose
nodeName
property is set to the attribute name. The
nodeValue
property is set to the attribute value. For example,
suppose you had this element:
<p style=”color: red” id=”p1”>Hello world!</p>
Also, suppose that the variable
oP
that contains a reference to this element. You can access the value of
the
id
attribute like this:
var sId = oP.attributes.getNamedItem(“id”).nodeValue;
Of course, you could access this
id
attribute numerically, which is a little less intuitive:
var sId = oP.attributes.item(1).nodeValue;
You can change the
id
attribute by setting a new value to the
nodeValue
property:
oP.attributes.getNamedItem(“id”).nodeValue = “newId”;
Attr
nodes also have a
value
property that is exactly equal (and kept in sync with) the
nodeValue
property, as well as a
name
property that is kept in sync with
nodeName
. You use any of these properties
to modify or change the attributes.
Because this method is a little bit cumbersome, the DOM also defines three element methods to aid in
the assignment of attributes:
?
getAttribute(
name
)
— same as
attributes.getNamedItem(
name
).value
?
setAttribute(
name
,
newvalue
)
— same as
attributes.getNamedItem(
name
).value =
newvalue
?
removeAttribute(
name
)
— same as
attributes.removeNamedItem(
name
)
These methods are helpful in that they deal directly with the attribute values, completely hiding the
Attr
nodes. So, to retrieve the
id
attribute of the
<p />
used earlier, you can just do this:
var sId = oP.getAttribute(“id”);
And to change the ID, you can do this:
oP.setAttribute(“id”, “newId”);
As you can see, these methods are much less verbose than using the
NamedNodeMap
methods.
Keep in mind that each of these methods returns an
Attr
node, not the value of the
attribute.
170
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 170


JavaScript EditorFree JavaScript Editor     Ajax Editor


©