Element.setAttributeNS() adds a new attribute or changes the value of an attribute with the given namespace and qualified name (MDN). For normal HTML without a namespace, prefer setAttribute().
Pass the required arguments shown below. Check return values and browser support before you rely on the result.
Syntax
Call el.setAttributeNS. Start with this line.
JavaScript
el.setAttributeNS(ns, qName, value)
Call
What it does
el.setAttributeNS(ns, qName, value)
Primary signature.
el.setAttributeNS(...)
Call with the arguments your case needs.
Built into the browser. Call setAttributeNS(...) on an Element — no import required.
MDN: when no namespace is needed, use the simpler non-NS API.
JavaScript
const btn = document.getElementById("btn");
// Everyday HTML — no namespace
btn.setAttribute("aria-label", "Save");
// Only when you truly need a namespace
btn.setAttributeNS(
"http://example.com/ns",
"ex:demo",
"1"
);
console.log(btn.getAttribute("aria-label"));
Security. Still avoid XSS-sink attributes from untrusted input.
Compatibility
Browser Support
Element.setAttributeNS() is Baseline Widely available (MDN, since July 2015). It is not Deprecated, Experimental, or Non-standard. Trusted Types enforcement for unsafe attributes depends on CSP / browser support.
✓ Baseline Widely available
Element.setAttributeNS()
Set or update a namespaced attribute by URI and qualified name. Prefer setAttribute() for ordinary HTML.
BaselineWidely available
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
Android WebViewSupported · Modern WebView
Full support
setAttributeNS()Baseline
Bottom line: Fully supported. Use for real namespaces (SVG/XML); keep setAttribute() as the default for HTML.
Frequently Asked Questions
It adds a new attribute or changes the value of an attribute with the given namespace URI and qualified name (MDN).
No. MDN marks Element.setAttributeNS() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
undefined. There is no return value (MDN).
namespaceURI (string or ""), qualifiedName (e.g. "spec:align"), and value (string or trusted type) (MDN).
MDN: for HTML documents when you do not need a specific namespace, use setAttribute() instead.
Some attributes are XSS injection sinks (onclick, srcdoc, script URLs). Never pass untrusted strings to those — same security considerations as setAttribute() (MDN).