Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some innerHTML replacement in SVG/XML?

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.

like image 511
Sirko Avatar asked Mar 15 '12 15:03

Sirko


People also ask

Can innerHTML contain HTML tags?

innerHTML, innerText and textContent. The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags.

Why you shouldn't use innerHTML?

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 .

What is innerHTML in Dom?

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).


2 Answers

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));
like image 192
Robert Longson Avatar answered Sep 20 '22 06:09

Robert Longson


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.

like image 30
Erik Dahlström Avatar answered Sep 22 '22 06:09

Erik Dahlström