createAttributeNS (W3C DOM Core method)

Spec
Version Depr. Static
DOM2 No No
Browser support (more…)
IE7 FF1.5+ SA3+ OP9+
None Buggy Full Buggy
Returns
Attr
Throws
INVALID_CHARACTER_ERR, NAMESPACE_ERR

Example

var attr = document.createAttributeNS
    ('http://www.w3.org/XML/1998/namespace', 'xml:lang');

attr.nodeValue = 'es-ar';

document.documentElement.setAttributeNodeNS(attr);

The example above creates an xml:lang attribute in the XML namespace, assigns it the nodeValue es-ar and then adds it to the document element using setAttributeNodeNS.

So if the document element in question were the root of an XHTML document, like this:

<html xmlns="http://www.w3.org/1999/xhtml">

Then the operation above would result in this:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es-ar">

Arguments

namespace (DOMString) required

The namespaceURI of the attribute. A value of null means no namespace.

name (DOMString)

The qualified name of the attribute.

Description

Create an Attr node of the specified qualified name1 and namespace URI.

The created attribute can then be added to an Element using the setAttributeNodeNS method.

A value can be assigned to it using the specialized value property of Attr, or the more general nodeValue property of Node. The value is not parsed, so any entity references or other markup will be treated as literal text. To create an attribute containing entities the specification suggests to create an Attr node with appropriate Text and EntityReference nodes as children, then add it to an element using setAttributeNode, however in practise this rarely works (see Attr for details).

Return value

The created attribute node, with its name and nodeName set to the specified qualified name, its namespaceURI set to the specified namespace URI, its prefix extracted from the specified qualified name (or null if there is no prefix), its localName extracted from the qualified name, and an empty string value

Compatibility

Internet Explorer Firefox Safari Opera
5.5 6.0 7.0 1.5 2.0 3.0 1.3 2.0 3.0 9.0 9.5
None None None Buggy Buggy Buggy Buggy Buggy Full Buggy Buggy

Internet Explorer doesn't implement this method (it returns undefined).

Safari 1.3 and 2 can't create valid attributes in the XML namespace. Attributes in that namespace are required to have the xml prefix, but including it causes a DOMException (code 14: NAMESPACE_ERR).

In Firefox and Opera an empty-string namespace is treated the same as a null namespace (ie. it's taken to mean no namespace, when it should be treated as a real namespace URI); only Safari 3 gets this right.

Footnotes

1 A qualified name is comprised of a local name, plus an optional prefix delimited with a colon, for example xml:lang.

User-contributed notes

There are no comments yet.

Related Products