Skip to content

What are namespaces in HTML?

It’s pretty straightforward I am trying to understand the namespaces in HTML.

What’s the difference between using these two commands. Why should be used createElementNS over createElement?

const a = document.createElementNS("http://www.w3.org/2000/svg", "svg")
const b = document.createElement("svg")

Resources:

Answer

Namespaces make it possible for different types of XML¹ to have the same tag with different meanings. Here’s an excerpt from Namespaces crash course on MDN:

It has been a long standing goal of the W3C to make it possible for different types of XML based content to be mixed together in the same XML file. For example, SVG and MathML might be incorporated directly into an XHTML based scientific document. Being able to mix content types like this has many advantages, but it also required a very real problem to be solved.

Naturally, each XML dialect defines the meaning of the markup element names described in its specification. The problem with mixing content from different XML dialects in a single XML document is that the elements defined by one dialect may have the same name as elements defined by another. For example, both XHTML and SVG have a element. How should the user agent distinguish between the two? In fact how does the user agent tell when XML content is something it knows about, and not just a meaningless XML file containing arbitrary element names unknown to it?

In your specific example, the difference is that createElement("svg") creates an HTML element with the tag name svg (which doesn’t exist, there is no HTML element with that tag name). But createElementNS("http://www.w3.org/2000/svg", "svg") creates an SVG element with the tag name svg (which does exist).

It matters because the SVG element has defined behavior and various methods and such you may want. Trying to create it as an HTML element, you don’t get those behaviors and methods:

const a = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const b = document.createElement("svg");

console.log("a instanceof SVGSVGElement?", a instanceof SVGSVGElement); // a instanceof SVGSVGElement? true
console.log("b instanceof SVGSVGElement?", b instanceof SVGSVGElement); // b instanceof SVGSVGElement? false

console.log("typeof a.currentScale:", typeof a.currentScale); // typeof a.currentScale: number
console.log("typeof b.currentScale:", typeof b.currentScale); // typeof b.currentScale: undefined

¹ HTML isn’t XML, but does sometimes have XML embedded in it (for instance: SVG). (There’s XHTML, which is XML, but note that XHTML is not HTML.)