XML DOM setAttributeNS() Method
Definition and Usage
The setAttributeNS() method creates or changes an attribute with a namespace.
Syntax:
elementNode.setAttributeNS(name,value)
Parameters | Description |
---|---|
ns | Required. Specifies the namespace URI of the attribute to be set. |
name | Required. Specifies the name of the attribute to be set. |
value | Required. Specifies the value to be set for the attribute. |
Description
This method is similar to setAttribute() methodSimilarly, the attributes to be created or set are specified by the namespace URI and qualified name (composed of the namespace prefix, colon, and local name within the namespace) together. In addition to changing the value of an attribute, this method can also change the namespace prefix of the attribute.
Only XML documents that use namespaces will use this method. Browsers that do not support XML documents may not implement this method.
Example
In all the examples, we will use XML files books_ns.xmlas well as JavaScript functions loadXMLDoc().
Example 1
The following code adds an "edition" attribute to the first <book> element in "books_ns.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
Example 2
The following code changes the value of the "lang" attribute of the first <title> element in "books_ns.xml":
xmlDoc=loadXMLDoc("books_ns.xml");
x=xmlDoc.getElementsByTagName("title")[0];
ns="http://www.codew3c.com/children/";
x.setAttributeNS(ns,"c:lang","italian");
document.write(x.getAttributeNS(ns,"lang"));
Output:
italian