For more tips like this, sign up to the weekly newsletter!
Use createElementNS when creating SVG elements
When you programmatically create an SVG element, a common error is to create it exactly the same way as you would any other elements:
const circle = document.createElement("circle");
...
document.querySelector("svg").appendChild(circle);
This produces no errors, but also no circles. But interestingly, the circle
is in the DOM, but it is not shown.
Use createElementNS
The solution is rather easy, just replace the createElement
with createElementNS
and supply the http://www.w3.org/2000/svg
namespace:
const nsCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
...
document.querySelector("svg").appendChild(nsCircle);
Why the namespace?
SVG was defined as an XML namespace that can be embedded into HTML, and it is required to prevent the clashing of element names.
Other namespaces
So, SVG is a different namespace, are there others?
Yes, for example, Firefox's XUL. Just look at that namespace URL: http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul