dom – Succinct construction of SVG nodes in JavaScript

dom – Succinct construction of SVG nodes in JavaScript

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

Note that the parent node will need to have an explicit namespace so that it gets parsed correctly i.e. the String would need to look like this:

var stringContainingXMLSource = <radialGradient xmlns=http://www.w3.org/2000/svg id=gradient ...

Then you can do

defs.appendChild(document.importNode(doc.documentElement));

Some UAs also allow doc.rootElement instead of doc.documentElement but apparently not all.

There isnt a direct markup property, but you can use DOMParser.parseFromString() to parse some XML into a new SVG document and importNode it across. Or, you can use innerHTML to set the content of a container HTML element and pull the SVG nodes out of the result.

But string-slinging gets a bit mucky—as soon as you want to bring in variable content or attribute values, its easy to do a string concatenation without remembering proper escaping, leading to cross-site-scripting problems. Its nice to be able to keep everything in a world of objects and properties rather than encoded markup when you can.

Admittedly the uber-verbose DOM API doesnt make that easy, but you can write shortcut functions to call the DOM methods for you, allowing you to write something like:

xml(SVG, defs, {}, [
    xml(SVG, radialGradient, {id: gradient, cx: 50%, cy: 50%, fx: 50%, fy: 50% r: 50%}, [
        xml(SVG, path, {offset:   0%, stop-color: #568f82, stop-opacity: 1}),
        xml(SVG, path, {offset: 100%, stop-color: #568f82, stop-opacity: 0})
    ])
])

which is a lot easier to cope with.

dom – Succinct construction of SVG nodes in JavaScript

If you want even more concise syntax and you are willing to use libraries, consider trying Raphaël or svg.js.

Leave a Reply

Your email address will not be published. Required fields are marked *