document.createElement("svg")
TIL: Creating SVG elements in the HTML DOM is…hella funny. Or heartbreaking, I’m not sure which.
HTML is so allergic to namespaces that HTML5 co-opts all of the MathML and SVG names and stuffs them into HTML rather than managing distributed extensibility with namespaces.
(I have no interest in re-litagating the dispute about namespaces in HTML. Namespaces lost. Some declare this a victory, some…have other opinions.)
So, I’m fiddling with some JavaScript and I want to create an SVG element. Easy peasy, right?
let svg = div.querySelector(".copyVerbIcon");
if (!svg) {
// It doesn’t exist yet, so create it.
svg = document.createElement("svg");
div.insertBefore(svg, div.firstChild);
}
Now we’ve inserted an SVG element in that div
; it’ll show up in the
tree and we can set classes on it, style it, add attributes, setup its
event listener, etc. Right?
Yes, you can do those things, but it won’t work. You have to create the SVG element in the SVG namespace in order for it to work:
svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
Because why? Because the tagName
is in upper case if you create it
without a namespace? Because some other reason? My cursory exploration
didn’t turn up anything that appeared to be a definitive on that
point.
I don’t know whether to [expletive] laugh or cry.