Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...