Copy (clone) an SVG element

Asked

Viewed 409 times

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 and y for smaller values (not to exit outside the screen) and change the cloned element ID. You can show how your code calls this function?

1 answer

3


First, insert the clone into the DOM, then modify the attributes (and make sure you’re calling the function clone() 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>

  • Thanks, it works. And now I want to change the id of the object. I try that newrect.id = "rect2"; but it doesn’t change.

  • Try newrect.setAttribute( 'id', 'rect2' ); after you put it in the DOM. From browser to browser I think the implementations vary a little.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.