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 container.
var templ = '<span>{myText}</span>'
var newContent = templ.replace( '{myText}', someVariable );
document.querySelector( '#myContainer' ).innerHTML = newContent;
This way I can take advantage of the browser's HTML parser and do not have to repeatedly use document.createElement()
. The later can be quite cumbersome, if the templates grows beyond a few elements.
In SVG, however, there is no property on the elements as innerHTML
or even innerSVG
for that matter.
So my question is: Is there anything I can use in SVG ro resemble the approach from the example above or am I stuck with document.createElement()
(or respectivly some lib that uses it)?
As always with my questions: Vanilla JavaScript solutions are preferred, but any pointer to a lib providing a solution is appreciated.
innerHTML, innerText and textContent. The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags.
The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .
The innerHTML property is part of the Document Object Model (DOM) that allows Javascript code to manipulate a website being displayed. Specifically, it allows reading and replacing everything within a given DOM element (HTML tag).
You can use DOMParser to parse XML. You can then use importNode to get that into your existing document if you want via 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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With