In HTML I can build a simple templating system by providing a template in form of a string, replace some parts of it and then assign it using innerHTML
to some
Check out the innerSVG javascript shim, it provides the functionality you want.
2014 update: The DOM parsing spec defines innerHTML
and outerHTML
on Element
, which makes these available on svg and xml elements. This has been shipping in Blink for a while now, first versions to support this was Chrome 32 / Opera 19, more details can be found in this bugreport.
How about my innerSVG shim? CoffeeScript source is below, compiled JavaScript is on https://gist.github.com/2648095
# Important: You must serve your pages as XHTML for this shim to work,
# otherwise namespaced attributes and elements will get messed up.
Object.defineProperty SVGElement.prototype, 'innerHTML',
get: () ->
$temp = document.createElement 'div'
$node = @cloneNode true
for $child in $node.children
$temp.appendChild $child
return $temp.innerHTML
set: (markup) ->
while @firstChild
@firstChild.parentNode.removeChild @firstChild
markup = "<svg id='wrapper' xmlns='http://www.w3.org/2000/svg'>#{markup}</svg>"
$div = document.createElement 'div'
$div.innerHTML = markup
$svg = $div.querySelector 'svg#wrapper'
for $element in $svg.children
@appendChild $element
enumerable : false
configurable : true
With jQuery, you can do it this way:
Let's suppose your svgString
contains your svg image after the replacing operations.
$(svgString)[0]
to create a svg tag corresponding to your string. Then you can append this element where you want in the dom to draw the image.
I hope this helps
You can use DOMParser to parse XML: https://developer.mozilla.org/en/Parsing_and_serializing_XML you can then use importNode to get that into your existing document if you want: https://developer.mozilla.org/en/DOM/document.importNode to end up with something like this...
var doc = new DOMParser().parseFromString(
'<svg xmlns="http://www.w3.org/2000/svg"><circle cx="100" cy="100" r="20"/></svg>',
'application/xml');
someElement.appendChild(
someElement.ownerDocument.importNode(doc.documentElement, true));
More simply, document.querySelector('#myContainer').textContent = newContent;
has pretty good support, def. to IE9+, Safari, FF, Chrome.
Mike Bostock's my hero for these kinds of things: the D3.js source code is my go-to for SVG questions.
It looks like at least on Chrome and Safari, you can wrap your SVG element in an HTML element and ask for innerHTML
. The following HTML file renders a red rectangle, even though the SVG source specifies green.
<body>
<div id="wrapper">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="120" height="120" viewBox="0 0 236 120">
<rect x="14" y="23" width="250" height="50" fill="green" stroke="black" stroke-width="1" />
</svg>
</div>
<script>
var el = document.getElementById('wrapper');
var t = el.innerHTML;
t = t.replace(/green/g, "red");
el.innerHTML = t;
</script>
</body>