setNamedItem (W3C DOM Core method)
var attrs = document.getElementsByTagName('link').item(0).attributes; var media = document.createAttribute('media'); media.nodeValue = 'all'; attrs.setNamedItem(media);
The example above saves the
attributes collection of an HTML
link element, then creates a new attribute node with
media and the value
and assigns it to that collection.
If a node with that name already
exists in the collection then it will be overwritten with the new value;
otherwise a new item will be added, and therefore a new attribute node
will apply to the original
Add a specified node to a
If a node with that name
already exists in the map, it will be replaced. For certain kinds of node
— where all instances have the same name (such as
#comment) — it's not possible to store more than one
instance of such a node within a single node map, because the names would
clash. The DOM specification considers this preferable to implementing
If the new node replaces an
existing node, the previously existing node is returned;
null is returned.
Internet Explorer 5.5 in HTML doesn't implement this method (it returns undefined).
Explorer 6 and 7 in HTML this method does not always return
null when adding to an attributes collection where the
specified node didn't previously exist; it returns
an empty string, depending on what type of value IE considers the
attribute to have (please see
Attr for more
information on attribute types in IE).
Explorer in XML returns the newly set value, rather than the
previously set value or
As an added conundrum, the MSDN documentation for this method
says that "an attribute that is set with this method does not have
to apply to the element". However in tests, created attributes
added to an
attributes collection do
indeed apply to their owning element, so I have no idea what situation
they might be talking about.