files/en-us/web/api/element/setattributens/index.md
{{ APIRef("DOM") }}
[!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 ({{domxref("TrustedHTML")}}, {{domxref("TrustedScript")}}, or {{domxref("TrustedScriptURL")}}) instead of strings for those attributes that require them, and enforcing trusted types. See Security considerations in {{domxref("Element.setAttribute()")}} for more information.
The setAttributeNS() method of the {{domxref("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 {{domxref("Element.setAttribute()", "setAttribute()")}} method instead.
Note that setAttributeNS() is the only method for namespaced attributes which expects the fully qualified name, i.e., "namespace:local-name".
setAttributeNS(namespace, name, value)
namespace
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:
onclick and onload, require a {{domxref("TrustedScript")}}.Trusted types are not enforced for other attributes, so a string or any trusted type may be passed.
None ({{jsxref("undefined")}}).
let d = document.getElementById("d1");
d.setAttributeNS(
"http://www.mozilla.org/ns/specialspace",
"spec:align",
"center",
);
The Setting unsafe attributes example in setAttribute() shows how you might use setAttributeNS() with the trusted types.
{{Specifications}}
{{Compat}}