Reputation: 1107
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.
Upvotes: 0
Views: 70
Reputation: 896
I'm pretty sure there is more than one way (and this one wont be the best ?), but you can try:
var svg = '<g><circle cx="10" cy="50" r="20"/><rect width="200" height="400" /> </g>';
var e = document.getElementById("msvg");
var svgObj = (new DOMParser()).parseFromString(svg, 'application/xml');
e.innerHTML = svgObj.documentElement.outerHTML;
Upvotes: 0
Reputation: 10470
To access the first child of nodeelem
, you need to use nodeelem.firstChild
instead of nodeelem.content.firstChild
.
Demo: https://jsfiddle.net/iRbouh/su3xrfd9/
Upvotes: 1