akaltar akaltar - 2 months ago 5
HTML Question

Appending SVG elements from SVG code

I have some base HTML like:

<svg id="msvg"></svg>

I want to add (for example) a
<g><circle cx="10" cy="50" r="20"/><rect width="200" height="400" /> </g>

Element into my SVG.

The element is given as a string in JavaScript.

I have thought about something like this:

function addSVG(svg) {
var e = document.getElementById("msvg");
var nodeelem = document.createElementNS("http://www.w3.org/2000/svg", "template");
nodeelem.innerHTML = svg;

But this doesn't work.

I am using Chromium Embedded, so a chrome-specific answer is good too.


To access the first child of nodeelem, you need to use nodeelem.firstChild instead of nodeelem.content.firstChild.

Demo: https://jsfiddle.net/iRbouh/su3xrfd9/