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 asinjection sinks, and are potentially a vector forcross-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, orTrustedScriptURL) instead of strings for those attributes that require them, andenforcing trusted types.SeeSecurity considerations inElement.setAttribute() for more information.
ThesetAttributeNS() method of theElement 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 thesetAttribute() method instead.
Note thatsetAttributeNS() is the only method for namespaced attributes which expects the fully qualified name, i.e.,"namespace:local-name".
In this article
Syntax
setAttributeNS(namespace, name, value)Parameters
namespaceA string specifying the namespace of the attribute.
nameA string identifying the attribute by its qualified name; that is, a namespace prefix followed by a colon followed by a local name.
valueA 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:
- Event handler content attributes, such as
onclickandonload, require aTrustedScript. HTMLIFrameElement.srcdocrequire aTrustedHTMLinstance.HTMLScriptElement.srcrequire aTrustedScriptURLinstance.SVGScriptElement.hrefrequire aTrustedScriptURLinstance.
Trusted types are not enforced for other attributes, so a string or any trusted type may be passed.
- Event handler content attributes, such as
Return value
None (undefined).
Examples
>Basic usage
let d = document.getElementById("d1");d.setAttributeNS( "http://www.mozilla.org/ns/specialspace", "spec:align", "center",);Trusted types
TheSetting unsafe attributes example insetAttribute() shows how you might usesetAttributeNS() with thetrusted types.
Specifications
| Specification |
|---|
| DOM> # ref-for-dom-element-setattributens①> |