TIL: svg tags need a namespace on creation

TIL: svg tags need a namespace on creation
Photo by Neringa Hünnefeld / Unsplash

Recently, I embarked on a project to develop a small HTML parser as part of my experiments in web development. Alongside this, I created a runtime package to utilize the parsed tree in various web applications.

When you write a library from scratch to learn about something, you will inevitably create bugs too. And this was not different.

Typically, when creating HTML elements using the DOM API, we use document.createElement, passing the tag name of the element we want to create. This API works with standard HTML tags and custom elements that might not be even defined yet.

However, for SVG elements, that will not work so well. The elements will still be created, and adding them to a page will show the elements in the tree, but any part of that SVG image won't render. All children of that SVG tag will have zero width/height, and then the head scratching starts!

The solution: for any <svg> element, and any elements inside of it, document.createElementNS has to be used instead, with a namespace that tells the API which type of element we are creating:

const element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

And that's it.

Subscribe to darlanalv.es

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe