Element: setAttributeNS() method


目录

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 Element.setAttribute() for more information.

The setAttributeNS() method of the Element 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.

Syntax

setAttributeNS(namespaceURI, qualifiedName, value)

Parameters

Return value

None (undefined).

Exceptions

Examples

Basic usage

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 setAttributeNS() with the trusted types.

Specifications

Browser compatibility

See also


版本号 #3
由 壳壳虫 创建于 2026-10-31 03:27:53 UTC
由 cocobook-sync 更新于 2026-11-04 17:34:37 UTC