akaltar akaltar - 4 months ago 8
HTML Question

Appending SVG elements from SVG code

I have some base HTML like:

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


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;
e.appendChild(nodeelem.content.firstChild);
}


But this doesn't work.

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

Answer

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

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