Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

Cloning elements

Cloning elements

The following shows how to clone/duplicate elements.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
<svg xmlns=""
width="300" height="300">
<script type="text/ecmascript"><![CDATA[
function cloneRect(evt) {
var cloneElement =;
var newx = 25 + Math.random() * 200;
var newy = 70 + Math.random() * 150;

<linearGradient id="MyGradient">
<stop offset="5%" stop-color="red" />
<stop offset="95%" stop-color="yellow" />
<g id="firstGroup">
<rect width="70" height="50" x="40" y="5"
fill="url(#MyGradient)" stroke="blue" stroke-width="2"
<text x="150" y="30">Click on rectangle
<tspan x="150" dy="15">to clone it.</tspan>

Link to example 8 (clone_elements.svg) – in a separate window)

The advantage of cloning elements instead of creating them from scratch, is that existing attributes can be re-used and if a lot of attributes are shared, make the code shorter. In order to clone an element, a node reference is needed. From this node reference the method .cloneNode(false) can be called. A new element reference is returned that can be manipulated like any other element reference, as described above, e.g. using the method .setAttributeNS(). In this case the random generator to change the x and y values of the cloned element is used. All the other attributes (such as fill, onclick, stroke, etc.) remain the same. The argument false in the method .cloneNode() means that only the element and it’s attributes are cloned, but not any children. If this argument is set to true, a copy including the subtree under the specified node is returned. Finally, the cloned element needs to be appended again somewhere in the document tree, using e.g. the .appendChild() method. Remark: if an element that has a unique id as an attribute is cloned, be sure to either remove that id, or make it unique again using .setAttributeNS(null,"id",newUniqueId)