AskYous AskYous - 3 months ago 11
HTML Question

Can't append to SVG, even after using namespace

I'm trying to append a

circle
to an
svg
element using JavaScript. I when I created the circle, I found out you should use
createElementNS
rather then
createElement
. I did this, and the circle does appear in the HTML, but it still doesn't appear in the page. Here's my code:

let ns = 'http://www.w3.org/2000/svg';
let svg = document.getElementsByTagName('svg')[0];
let circle = document.createElementNS(ns, 'circle');

circle.setAttributeNS(ns, 'cx', 100);
circle.setAttributeNS(ns, 'cy', 100);
circle.setAttributeNS(ns, 'r', 10);
circle.style.fill = 'red';

svg.appendChild(circle);


The output is:

<svg><circle cx="100" cy="100" r="10" style="fill: red;"></circle></svg>


But the view is empty. See a Codepen here.

Answer

After creating the circle element using the createElementNS you don't need the setAttributeNS, you should use the setAttribute function:

var ns = 'http://www.w3.org/2000/svg';
var svg = document.getElementsByTagName('svg')[0];
var circle = document.createElementNS(ns, 'circle');

circle.setAttribute('cx', 100);
circle.setAttribute('cy', 100);
circle.setAttribute('r', 10);
circle.style.fill = 'red';

svg.appendChild(circle);
svg{ width: 100%; height: 100%; background-color: blue; }
<svg></svg>