How do I get the SVG DOM root, and start adding children to it, programmatically, instead of adding SVG elements by markup?
Seen in action: http://phrogz.net/SVG/create-circle.svg
Because it can be so cumbersome to issue all those setAttribute
calls, I often use a function like this:
// Create an SVG element on another node with a set of attributes.
// Attributes with colons in the name (e.g. 'xlink:href') will automatically
// find the appropriate namespace URI from the SVG element.
// Optionally specify text to create as a child node, for example
// createOn(someGroup,'text',{x:100,'text-anchor':'middle'},"Hello World!");
function createOn(root,name,attrs,text){
var doc = root.ownerDocument, svg = root;
while (svg.tagName!='svg') svg = svg.parentNode;
var el = doc.createElementNS(svg.namespaceURI,name);
for (var a in attrs){
if (!attrs.hasOwnProperty(a)) continue;
var p = a.split(':');
if (p[1]) el.setAttributeNS(svg.getAttribute('xmlns:'+p[0]),p[1],attrs[a]);
else el.setAttribute(a,attrs[a]);
}
if (text) el.appendChild(doc.createTextNode(text));
return root.appendChild(el);
}
In action, the above file becomes more simply:
Seen in action: http://phrogz.net/svg/create-circle-2.svg