Copy (clone) an SVG element

4

I want to "clone" an SVG rect in JavaScript when I click a button. I tried this code, but it did not 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);
}
    
asked by anonymous 20.10.2014 / 02:19

1 answer

3

First, insert the clone into the DOM, then modify the attributes (and make sure you're calling the clone() function correctly in your code):

function clone(){
  var newrect = document.getElementById('rect').cloneNode(true);
  document.getElementById('svg').appendChild(newrect);
  newrect.setAttribute("x", 100);
  newrect.setAttribute("y", 100);
}


Demonstration:

function clone(){
  var newrect = document.getElementById('rect').cloneNode(true);
  document.getElementById('svg').appendChild(newrect);
  newrect.setAttribute("x", 100);
  newrect.setAttribute("y", 100);
}
<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>
<button onClick="clone();this.disabled=true">Clonar</button>
    
20.10.2014 / 02:33