4
I want to "clone" an SVG rect in Javascript when I click a button. I tried this code, but it didn’t work.
<svg id="svg">
<rect id="rect" x="5" y="25" width="50" height="50" stroke="#0E0E0E" style="fill:red; stroke-width:1" />
<text id =txtrect x="5" y="35" font-family="Verdana" font-size="11" fill="white" >
Rect1
</text>
</svg>
function clone(){
var newrect = document.getElementById('rect').cloneNode(true);
newrect.setAttribute("x", 300);
newrect.setAttribute("y", 300);
newrect.style.position = 'absolute';
document.getElementById("svg").appendChild(newrect);
}
Can you explain better the "didn’t work"? Your code works for me. Eventually you should change the
x
andy
for smaller values (not to exit outside the screen) and change the cloned element ID. You can show how your code calls this function?– Sergio