Creating an SVG DOM element from a String

You can use DOMParser to parse an XML string.

var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");

The root element for the parsed string will be doc.documentElement

For this to work properly cross-browser you’ll need to set the html namespace i.e. your string will need to look like this…

var svg2='<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" ...

Leave a Comment