JavaScript Element setAttributeNS() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.setAttributeNS() is an instance method that sets a namespaced attribute by namespace URI and qualified name. Learn MDN’s spec:align example, SVG xlink:href, when to prefer setAttribute(), XSS injection-sink warnings, and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Args

NS, name, value

03

Returns

undefined

04

SVG/XML

xlink, custom NS

05

Security

XSS sinks

06

Status

Baseline widely

Introduction

Most HTML pages use setAttribute("class", "active") for plain attributes. SVG and XML also need namespaced attributes tied to a namespace URI—for example xlink:href on an SVG link.

element.setAttributeNS(namespaceURI, qualifiedName, value) adds or updates that namespaced attribute (MDN). For HTML attributes without a namespace, use setAttribute() instead.

💡
Security note (MDN)

Like setAttribute(), some attributes are injection sinks (e.g. onclick, srcdoc, script src). Never pass untrusted user input to those. Use safe alternatives or Trusted Types when enforced.

This page is part of JavaScript Element. Pair with getAttributeNS(), removeAttributeNS(), and setAttributeNodeNS().

Understanding the setAttributeNS() Method

Calling el.setAttributeNS(ns, name, value) sets a namespaced attribute on el. Read it back with getAttributeNS(); delete with removeAttributeNS().

  • It is an instance method on Element.
  • namespaceURI — the attribute namespace URI (MDN).
  • qualifiedNameprefix:localName or localName (MDN).
  • value — string or trusted type (MDN).
  • Returns undefined.
  • For Attr-node workflows, use setAttributeNodeNS() instead (MDN).

📝 Syntax

General form of Element.setAttributeNS (MDN):

JavaScript
setAttributeNS(namespaceURI, qualifiedName, value)

Parameters

ParameterTypeDescription
namespaceURIstringThe namespace URI of the attribute (MDN).
qualifiedNamestringThe attribute name, often prefix:localName (MDN).
valuestring or trusted typeThe value to assign. Non-strings are converted to strings (MDN).

Return value

TypeDescription
undefinedNo return value (MDN).

Exceptions

  • InvalidCharacterError — invalid characters in qualifiedName (MDN).
  • TypeError — when Trusted Types are enforced and a raw string is passed to a sink attribute (MDN).

Common patterns

JavaScript
const MY_NS = "http://www.mozilla.org/ns/specialspace";
const XLINK = "http://www.w3.org/1999/xlink";
const el = document.getElementById("target");

// MDN — custom namespaced attribute
el.setAttributeNS(MY_NS, "spec:align", "center");

// SVG link target
const anchor = document.querySelector("svg a");
anchor.setAttributeNS(XLINK, "xlink:href", "https://example.com");

// Read back
console.log(el.getAttributeNS(MY_NS, "align")); // "center"

// Plain HTML? Use setAttribute instead (MDN)
el.setAttribute("data-id", "42");

⚡ Quick Reference

GoalCode
Set namespaced attrel.setAttributeNS(ns, "spec:align", "center")
Set SVG xlink:hrefel.setAttributeNS(XLINK, "xlink:href", url)
Read back valueel.getAttributeNS(ns, "align")
Remove namespaced attrel.removeAttributeNS(ns, "align")
Plain HTML attributeel.setAttribute("class", "active")
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Element.setAttributeNS().

Returns
undefined

No value

Baseline
widely

Since July 2015

Args
ns,name,val

Three params

HTML
setAttribute

No namespace

📋 setAttributeNS() vs related APIs

setAttributeNS(ns, name, val)setAttribute(name, val)setAttributeNodeNS(attr)
NamespaceExplicit URI parameterNone (HTML attrs)On the Attr node
InputURI + qualified name + valueName + valueNamespaced Attr object
ReturnsundefinedundefinedReplaced Attr (if any)
Best forSVG/XML namespaced writesEveryday HTML attributesClone / Attr workflows
MDN guidancePreferred for simple NS setsWhen no namespace neededWhen you need the Attr node

Examples Gallery

Examples follow MDN Element.setAttributeNS() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN’s custom namespace demo and SVG xlink:href writes.

Example 1 — spec:align (MDN)

Set a custom namespaced attribute with MDN’s spec:align example.

JavaScript
const MY_NS = "http://www.mozilla.org/ns/specialspace";
const d = document.getElementById("d");

d.setAttributeNS(MY_NS, "spec:align", "center");

console.log(d.getAttributeNS(MY_NS, "align")); // "center"
Try It Yourself

How It Works

MDN: pass the namespace URI, qualified name (spec:align), and value. Verify with getAttributeNS() using the local name align.

📈 Practical Patterns

Update values, choose the right API, and avoid XSS sinks.

Example 3 — Update a Namespaced Value

Calling setAttributeNS() again replaces the existing namespaced attribute.

JavaScript
const MY_NS = "http://www.mozilla.org/ns/specialspace";
const el = document.getElementById("item");
// already has spec:align="left"

el.setAttributeNS(MY_NS, "spec:align", "right");

console.log(el.getAttributeNS(MY_NS, "align")); // "right"
Try It Yourself

How It Works

MDN: if the attribute already exists, the value is updated; otherwise a new namespaced attribute is added.

Example 4 — setAttributeNS() vs setAttribute()

Use the right method for namespaced vs plain HTML attributes (MDN).

JavaScript
const box = document.getElementById("box");

// Plain HTML — no namespace (MDN)
box.setAttribute("data-role", "panel");

// Namespaced custom attribute
const MY_NS = "http://www.mozilla.org/ns/specialspace";
box.setAttributeNS(MY_NS, "spec:align", "center");

console.log(box.getAttribute("data-role"));       // "panel"
console.log(box.getAttributeNS(MY_NS, "align")); // "center"
Try It Yourself

How It Works

MDN recommends setAttribute() for HTML attributes that do not need a namespace. Reserve setAttributeNS() for SVG, XML, and custom namespaces.

Example 5 — Safe vs Unsafe Attribute Writes

Set safe metadata; avoid injection-sink attributes with untrusted input (MDN).

JavaScript
const MY_NS = "http://www.mozilla.org/ns/specialspace";
const el = document.getElementById("widget");

// Safe — custom namespaced metadata
el.setAttributeNS(MY_NS, "spec:align", "center");

// Safe — plain data attribute
el.setAttribute("data-version", "1");

// Avoid: el.setAttribute("onclick", userInput);   // XSS sink
// Avoid: el.setAttributeNS(ns, "on:click", x); // still dangerous

console.log(el.getAttributeNS(MY_NS, "align")); // "center"
Try It Yourself

How It Works

MDN documents the same injection-sink warnings as setAttribute(). Use addEventListener for behavior, not attribute strings.

🚀 Common Use Cases

  • Setting xlink:href or other SVG namespaced attributes dynamically.
  • Writing custom XML namespace attributes in mixed SVG/HTML documents.
  • Updating namespaced metadata on elements parsed from XML.
  • Pairing with getAttributeNS() and removeAttributeNS() for full lifecycle.
  • Simple namespaced writes when you do not need an Attr node (vs setAttributeNodeNS()).
  • Leaving plain HTML attributes to setAttribute() (MDN).

🧠 How setAttributeNS() Updates Markup

1

Pass namespace, name, and value

el.setAttributeNS(MY_NS, "spec:align", "center") — three arguments (MDN).

Args
2

Resolve the namespace

The browser ties the attribute to namespaceURI and the qualified name (MDN).

Namespace
3

Add or update

If the namespaced attribute exists, update its value; otherwise create it (MDN).

Write
4

Markup reflects the change

Verify with getAttributeNS() or DevTools; return value is undefined.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, July 2015).
  • MDN: for HTML attributes without a namespace, use setAttribute() instead.
  • Some attributes are XSS injection sinks — never pass untrusted input to onclick, srcdoc, etc. (MDN).
  • For Attr-node workflows (clone, replace), use setAttributeNodeNS() (MDN).
  • Do not use setAttributeNS(ns, name, null) to delete — use removeAttributeNS().
  • Related: getAttributeNS(), hasAttributeNS(), removeAttributeNS(), JavaScript hub.

Browser Support

Element.setAttributeNS() is Baseline Widely available (MDN: across browsers since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.setAttributeNS()

Set or update namespaced attributes by URI and qualified name — the standard DOM API for SVG and XML.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Supported in legacy IE
Yes
setAttributeNS() Excellent

Bottom line: Use setAttributeNS() for SVG/XML namespaced writes, setAttribute() for plain HTML, and setAttributeNodeNS() when you need Attr-node workflows.

Conclusion

Element.setAttributeNS() adds or updates namespaced attributes by URI and qualified name. It is Baseline widely available, returns undefined, and pairs naturally with getAttributeNS() and removeAttributeNS().

Continue with getAttributeNS(), setAttributeNodeNS(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use setAttributeNS() for SVG and XML namespaced attributes
  • Store namespace URIs in constants (XLINK, MY_NS)
  • Prefer setAttributeNS() over Attr-node APIs for simple writes (MDN)
  • Verify with getAttributeNS() after setting
  • Use setAttribute() for plain HTML attributes (MDN)

❌ Don’t

  • Pass untrusted strings to injection-sink attributes
  • Use setAttributeNS() when setAttribute() is enough
  • Expect a useful return value (it is undefined)
  • Confuse namespace URI with element namespace
  • Use attribute strings for event handlers — use addEventListener

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.setAttributeNS()

Set namespaced attributes — SVG, XML, and custom namespaces.

5
Core concepts
📄 02

Args

ns, name, value

Triple
🌐 03

SVG

xlink:href

Common
04

Baseline

widely available

Status
05

HTML

setAttribute()

Plain attrs

❓ Frequently Asked Questions

It adds a new attribute or changes the value of an attribute with the given namespace and qualified name (MDN).
No. MDN marks Element.setAttributeNS() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
undefined. There is no return value (MDN).
namespaceURI (string), qualifiedName (string, e.g. xlink:href), and value (string or trusted type) (MDN).
MDN: for HTML documents when you do not need to specify the attribute as part of a namespace, use setAttribute() instead.
Some attributes are XSS injection sinks (onclick, srcdoc, script src). Never pass untrusted strings to those. MDN documents the same security considerations as setAttribute().
Did you know?

MDN’s setAttributeNS() demo uses setAttributeNS("http://www.mozilla.org/ns/specialspace", "spec:align", "center")—the namespace URI and qualified name together identify the attribute, not just the local name.

Next: setCapture()

Learn the deprecated Gecko mouse-capture API and its modern replacement.

setCapture() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful