I have an svg element as plain text
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
How can I render this on a HTML page by inserting it with JavaScript/jquery without recreating every node with
document.createElementNS("", "svg")
(because otherwise it will not be rendered)
I have an svg element as plain text
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
How can I render this on a HTML page by inserting it with JavaScript/jquery without recreating every node with
document.createElementNS("http://www.w3/2000/svg", "svg")
(because otherwise it will not be rendered)
Share Improve this question edited Feb 20, 2016 at 10:38 Matthew 7,5901 gold badge27 silver badges49 bronze badges asked Feb 20, 2016 at 10:34 EntimonEntimon 1843 silver badges11 bronze badges3 Answers
Reset to default 2try the following code.
var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3/2000/svg" xmlns:xlink="http://www.w3/1999/xlink" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 30 30" enable-background="new 0 0 30 30" xml:space="preserve">'+
'<path fill="#156BB1" d="M22.906,10.438c0,4.367-6.281,14.312-7.906,17.031c-1.719-2.75-7.906-12.665-7.906-17.031S10.634,2.531,15,2.531S22.906,6.071,22.906,10.438z"/>'+
'<circle fill="#FFFFFF" cx="15" cy="10.677" r="3.291"/></svg>';
var mysvg = new Image();
mysvg.src = 'data:image/svg+xml,' + escape(svg);
and then use mysvg
variable to place it where ever you want within your html.
Use innerHTML to insert it.
document.documentElement.innerHTML = '<svg height="100" width="100">\n <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />\n</svg>'
do this with JQuery:
var str = '<svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>'
$("body").append(str)
working code here