Element: setAttributeNS() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

Warning: This method can take attribute values that are parsed as HTML, a script, or as a script URL, depending on the attribute. APIs like this are known as injection sinks, and are potentially a vector for cross-site scripting (XSS) attacks, if the value originally came from an attacker.

You can mitigate this risk by always passing the appropriate trusted type object (TrustedHTML, TrustedScript, or TrustedScriptURL) instead of strings for those attributes that require them, and enforcing trusted types. See Security considerations in must be provided interface adds a new attribute or changes the value of an attribute with the given namespace and name.

If you are working with HTML documents and you don't need to specify the requested attribute as being part of a specific namespace, use the setAttribute() method instead.

Note that setAttributeNS() is the only method for namespaced attributes which expects the fully qualified name, i.e., "namespace:local-name".

Syntax

js
setAttributeNS(namespace, name, value)

Parameters

namespace

A string specifying the namespace of the attribute.

name

A string identifying the attribute by its qualified name; that is, a namespace prefix followed by a colon followed by a local name.

value

A trusted type or string containing the value to assign to the attribute.

Trusted type instances must be passed for the following attributes when trusted types are enforced:

Trusted types are not enforced for other attributes, so a string or any trusted type may be passed.

Return value

None (undefined).

Examples

Basic usage

js
let d = document.getElementById("d1");
d.setAttributeNS(
  "http://www.mozilla.org/ns/specialspace",
  "spec:align",
  "center",
);

Trusted types

The Setting unsafe attributes example in setAttribute() shows how you might use for setAttributeNS() with the trusted types.

Specifications

Specification
DOM
# ref-for-dom-element-setattributens①

Browser compatibility

See also