JavaScript Document createElementNS() Method

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

What You’ll Learn

document.createElementNS() is an instance method that creates a new element with an explicit namespace URI and qualified name (see MDN Document: createElementNS()). Learn when you need it for SVG and MathML, how it differs from createElement(), common namespace strings, and five try-it labs.

01

Kind

Instance method

02

Args

ns + name

03

Returns

Element

04

Best for

SVG / MathML

05

vs HTML

createElement

06

Status

Baseline

Introduction

HTML pages often mix languages: HTML for layout, SVG for icons and charts, MathML for equations. Each language lives in its own namespace — a URI that tells the browser which vocabulary a tag belongs to.

document.createElementNS(namespaceURI, qualifiedName) creates an element in a chosen namespace. MDN notes this is useful when the parser cannot reliably infer the namespace — for example building SVG from JavaScript inside an HTML document.

💡
Remember the SVG gotcha

MDN: createElement("svg") in an HTML document returns an HTMLUnknownElement — the drawing will not render. Always use the SVG namespace with createElementNS.

For plain HTML tags (div, button, p), prefer the simpler createElement().

Related tutorials: createElement(), createAttributeNS(), appendChild().

Understanding document.createElementNS()

An instance method on the page’s document object (MDN Document interface).

  • namespaceURI — string identifying the element vocabulary (SVG, MathML, XHTML, …).
  • qualifiedNamelocalName or prefix:localName; initializes nodeName (MDN).
  • Return value — a new Element in that namespace (MDN).
  • Detached — still must be appended or inserted to appear on the page.
  • Options — optional is / customElementRegistry (same rules as createElement; MDN).
  • HTML shortcut — XHTML div via createElementNS is equivalent to createElement("div") (MDN).

📝 Syntax

General forms of Document.createElementNS (MDN):

JavaScript
createElementNS(namespaceURI, qualifiedName)
createElementNS(namespaceURI, qualifiedName, options)

Parameters

  • namespaceURI — namespace string to associate with the element. Important values (MDN):
    • XHTML — http://www.w3.org/1999/xhtml
    • SVG — http://www.w3.org/2000/svg
    • MathML — http://www.w3.org/1998/Math/MathML
  • qualifiedNameprefix:localName or localName. If prefix is xml or xmlns, the namespace URI must match the XML/xmlns namespaces (MDN).
  • options (optional) — object with is or customElementRegistry (only one may be set; MDN). Some browsers also accept a string for backward compatibility.

Return value

The new Element (MDN).

Exceptions

  • NamespaceError — invalid namespaceURI, empty URI with a prefix, or wrong URI for xml/xmlns prefixes (MDN).
  • InvalidCharacterErrorprefix or localName is not a valid name (MDN).
  • NotSupportedError — both is and customElementRegistry are specified (MDN).

MDN XHTML equivalence

JavaScript
const divElementXHTML = document.createElementNS(
  "http://www.w3.org/1999/xhtml",
  "div",
);

// Equivalent for plain HTML:
const divElementHTML = document.createElement("div");

🌐 Common namespace URIs

Keep these strings in constants so you do not mistype them.

VocabularynamespaceURIExample tags
HTML / XHTMLhttp://www.w3.org/1999/xhtmldiv, p, button
SVGhttp://www.w3.org/2000/svgsvg, circle, path
MathMLhttp://www.w3.org/1998/Math/MathMLmath, mi, mo

⚡ Quick Reference

GoalCode
SVG rootdocument.createElementNS(svgNS, "svg")
SVG circledocument.createElementNS(svgNS, "circle")
XHTML divcreateElementNS(xhtmlNS, "div")
Plain HTML divdocument.createElement("div")
Read namespaceel.namespaceURI
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createElementNS().

Returns
Element

namespaced

Needs
namespaceURI

+ qualifiedName

SVG tip
use NS

not createElement

Status
Baseline

since 2015

📋 createElementNS vs createElement for SVG

createElement("svg")createElementNS(svgNS, "svg")
Result typeHTMLUnknownElement (HTML doc)SVGSVGElement
Renders as SVG?No (MDN)Yes
Recommended?No for SVGYes for SVG
Best forHTML tags onlySVG / MathML / namespaces

Examples Gallery

Examples follow MDN Document: createElementNS() and practical SVG patterns beginners need first.

📚 Getting Started

XHTML equivalence and a real SVG drawing.

Example 1 — MDN: XHTML div equals createElement

Creating a div in the XHTML namespace matches a plain HTML div (MDN).

JavaScript
const xhtmlNS = "http://www.w3.org/1999/xhtml";

const divNS = document.createElementNS(xhtmlNS, "div");
const divHTML = document.createElement("div");

console.log(divNS.namespaceURI);  // "http://www.w3.org/1999/xhtml"
console.log(divHTML.namespaceURI); // "http://www.w3.org/1999/xhtml"
console.log(divNS instanceof HTMLDivElement); // true
Try It Yourself

How It Works

For HTML documents, everyday elements already live in the XHTML namespace. That is why createElement("div") is enough for normal UI work.

Example 2 — MDN: create an SVG circle

Build an svg root and a circle child with the SVG namespace.

JavaScript
const svgNS = "http://www.w3.org/2000/svg";

const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("width", "100");
svg.setAttribute("height", "100");

const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute("cx", "50");
circle.setAttribute("cy", "50");
circle.setAttribute("r", "40");
circle.setAttribute("fill", "steelblue");

svg.appendChild(circle);
document.body.appendChild(svg);

console.log(svg instanceof SVGSVGElement);       // true
console.log(circle instanceof SVGCircleElement); // true
Try It Yourself

How It Works

Every SVG tag you create in script needs the same SVG namespace URI. Then set geometry attributes and append the tree to the page.

📈 Practical Patterns

The wrong SVG call, namespace inspection, and a tiny MathML sample.

Example 3 — Why createElement("svg") fails (MDN)

Compare the wrong HTML-only call with the namespaced call.

JavaScript
const wrong = document.createElement("svg");
const right = document.createElementNS("http://www.w3.org/2000/svg", "svg");

console.log(wrong instanceof HTMLUnknownElement); // true
console.log(wrong instanceof SVGSVGElement);      // false
console.log(right instanceof SVGSVGElement);      // true
console.log(wrong.namespaceURI); // "http://www.w3.org/1999/xhtml"
console.log(right.namespaceURI); // "http://www.w3.org/2000/svg"
Try It Yourself

How It Works

Without the SVG namespace, the browser treats svg like an unknown HTML tag. Graphics APIs and rendering expect a real SVGSVGElement.

Example 4 — Inspect namespaceURI, localName, prefix

Read the identity properties after creation.

JavaScript
const svgNS = "http://www.w3.org/2000/svg";
const path = document.createElementNS(svgNS, "path");

console.log({
  namespaceURI: path.namespaceURI,
  localName: path.localName,
  prefix: path.prefix,
  nodeName: path.nodeName,
  tagName: path.tagName
});
Try It Yourself

How It Works

With no prefix in the qualified name, prefix is null. namespaceURI still carries the SVG vocabulary string.

Example 5 — Tiny MathML expression

Same idea for MathML: use the MathML namespace on every math tag.

JavaScript
const mathNS = "http://www.w3.org/1998/Math/MathML";

const math = document.createElementNS(mathNS, "math");
const mi = document.createElementNS(mathNS, "mi");
mi.textContent = "x";
math.appendChild(mi);

document.body.appendChild(math);
console.log(math.namespaceURI);
console.log(math.outerHTML);
// <math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>
Try It Yourself

How It Works

MathML tags created without the MathML namespace will not behave as math elements. Mirror the SVG habit: one constant URI for the whole subtree.

🚀 Common Use Cases

  • Dynamic SVG charts — build svg, path, and circle nodes from data.
  • Icons in JS — assemble small SVG icons without innerHTML.
  • MathML UIs — create equation markup programmatically.
  • Mixed documents — when HTML embeds other vocabularies (MDN).
  • Not for plain HTML — use createElement() for div, button, lists, etc.
  • Namespaced attributes — pair with createAttributeNS / setAttributeNS when needed.

🧠 How createElementNS() Works

1

Choose a namespace URI

MDN: SVG, MathML, or XHTML URI strings identify the vocabulary.

URI
2

Pass qualified name

Tag like "circle" or optionally prefix:localName.

Name
3

Configure attributes

Set geometry, fill, viewBox, and children while detached.

Setup
4

Append to the document

Insert the root so the browser can render the namespaced tree.

📝 Notes

  • MDN: Baseline Widely available since July 2015 (* some parts may vary).
  • Use createElementNS for SVG/MathML; use createElement for plain HTML (MDN).
  • createElement("svg") in HTML yields HTMLUnknownElement and will not render SVG (MDN).
  • Invalid namespace or name values throw (MDN: NamespaceError / InvalidCharacterError).
  • Do not set both is and customElementRegistry (MDN).
  • Store namespace URIs in constants to avoid typos.
  • Related: createElement(), createAttributeNS(), appendChild().

Browser Support

Document.createElementNS() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project. Optional options features may have varying support.

Baseline Widely available

Document.createElementNS()

Create SVG, MathML, and other namespaced elements across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createElementNS() Wide

Bottom line: Use createElementNS for SVG and MathML. Prefer createElement for everyday HTML tags.

Conclusion

document.createElementNS(namespaceURI, qualifiedName) builds elements that belong to a specific vocabulary. For SVG and MathML inside HTML pages, it is the correct tool — createElement alone will not produce real SVG nodes.

Continue with createElement(), createEvent(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use the SVG namespace for every SVG tag you create
  • Keep namespace URIs in named constants
  • Prefer createElement for plain HTML
  • Check el instanceof SVGSVGElement when debugging
  • Append the root so the graphic can render

❌ Don’t

  • Call createElement("svg") expecting a real SVG (MDN)
  • Mix HTML-namespace children into SVG without knowing the rules
  • Typo the namespace URI string
  • Set both is and customElementRegistry
  • Forget to insert the detached element into the DOM

Key Takeaways

Knowledge Unlocked

Five things to remember about createElementNS()

Namespaced elements for SVG, MathML, and more.

5
Core concepts
🎨02

SVG

must use NS

gotcha
📄03

HTML

createElement OK

simpler
04

Returns

Element

typed
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createElementNS() creates a new element with a specified namespace URI and qualified name. Use it for SVG, MathML, or other namespaces in mixed documents.
No. MDN marks Document.createElementNS() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard. Some optional options features may vary.
MDN: createElement() is simpler for plain HTML elements. Prefer createElementNS() when the parser cannot reliably infer the namespace — especially SVG or MathML inside HTML.
MDN: In an HTML document, createElement("svg") returns an HTMLUnknownElement, so the SVG will not render correctly. You must use createElementNS with the SVG namespace http://www.w3.org/2000/svg.
MDN highlights: XHTML http://www.w3.org/1999/xhtml, SVG http://www.w3.org/2000/svg, and MathML http://www.w3.org/1998/Math/MathML.
A new Element (MDN). For SVG tags in the SVG namespace you get SVG-specific interfaces such as SVGSVGElement or SVGCircleElement.
Did you know?

The SVG namespace string http://www.w3.org/2000/svg looks like a web address, but the browser does not fetch it. It is an identifier — a unique name for the SVG vocabulary — so every SVG element can be recognized correctly in mixed documents.

Next: createEvent()

Learn the deprecated createEvent factory and why modern code uses Event constructors instead.

createEvent() →

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