AskYous AskYous - 1 year ago 74
HTML Question

Can't append to SVG, even after using namespace

I'm trying to append a

to an
element using JavaScript. I when I created the circle, I found out you should use
rather then
. 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 = '';
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); = 'red';


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 Source

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

var ns = '';
var svg = document.getElementsByTagName('svg')[0];
var circle = document.createElementNS(ns, 'circle');

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

svg{ width: 100%; height: 100%; background-color: blue; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download