0

I'm trying to create an SVG shape and append it to an element in my DOM.

The following JS appends the <svg> to the intended node, but doesn't render a purple background on the page:

const svgBox = document.createElement("svg");
svgBox.setAttribute('height', 150);
svgBox.setAttribute('width', 800);
svgBox.setAttribute('style', 'background-color:purple;');
const div = document.getElementsByTagName('div')[0];  // this does exist
div.appendChild(svgBox);

Here is a JSFiddle showing the equivalent HTML that does work (if I comment the tag back in) but the above JS not working. I've stripped this down from a more complex use case and have demonstrated to myself I'm missing some crucial basic display principle.

Jacob Walls
  • 873
  • 3
  • 15

1 Answers1

1

An SVG is a namespaced element, so you have to use createElementNS instead of createElement - to understand why check out this answer

Here is a working example:

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

svgBox.setAttribute('height', 150);
svgBox.setAttribute('width', 800);
svgBox.setAttribute('style', 'background-color:purple;');

const div = document.getElementsByTagName('div')[0]; // this does exist
div.appendChild(svgBox);
<div>
</div>

D-Money
  • 2,375
  • 13
  • 27