I have an inline SVG with in an HTML5 document, and would like to add with jQuery (or plain JavaScript if needed).
I know how to add a rect, circle or other form, but I’m not able yet to reuse an existing .
Here is a test on jsFiddle: http://jsfiddle.net/nhoizey/uDVbn/
The SVG:
<svg width="300" height="300">
<symbol id="piece"><circle cx="50" cy="50" r="40" fill="green" /></symbol>
<circle cx="70" cy="90" r="20" stroke="blue" fill="white" />
</svg>
The JavaScript:
// it works!
var rect = $(document.createElementNS("http://www.w3.org/2000/svg","rect"))
.attr({
x: 10,
y: 30,
width: 50,
height: 70,
stroke: "red",
fill: "white"
});
$("svg").append(rect);
// it doesn't work
var newPiece = $(document.createElementNS("http://www.w3.org/2000/svg","use"))
.attr({
"xlink:href": "#piece",
transform: "translate(100, 100)"
});
$("svg").append(newPiece);
I know there is a jQuery SVG plugin, but would like to keep it as light as possible.
The proper way to add href attribute is to use setAttributeNS.