XML DOM setAttributeNode() Method
Definition and Usage
The setAttributeNode() method adds a new attribute node.
If the element already has an attribute with the specified name, that attribute will be replaced by the new attribute. If the new attribute replaces an existing attribute, the replaced attribute will be returned, otherwise NULL will be returned.
Syntax:
elementNode.setAttributeNode(att_node)
Parameter | Description |
---|---|
att_node | Required. Specifies the attribute node to be set. |
Description
This method adds a new Attr node to the attribute collection of the Element node. If the current Element already has an attribute with the same name, this method will replace that attribute with the new one and return the replaced Attr node. If there is no such attribute, this method will define a new attribute for the Element.
Generally, setAttribute() Methodis simpler than using setAttributeNode().
Example
In all examples, we will use the XML file books.xml, and JavaScript functions loadXMLDoc().
The following code adds the "edition" attribute to all <book> elements in "books.xml":
xmlDoc=loadXMLDoc("books_ns.xml");
x=xmlDoc.getElementsByTagName("book")[0];
ns="http://www.codew3c.com/edition/";
x.setAttributeNS(ns,"edition","first");
document.write(x.getAttributeNS(ns,"edition"));
Output:
first