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"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="300" height="300">
<script type="text/ecmascript"><![CDATA[
function cloneRect(evt) {
var cloneElement = evt.target.cloneNode(false);
var newx = 25 + Math.random() * 200;
var newy = 70 + Math.random() * 150;
cloneElement.setAttributeNS(null,"x",newx);
cloneElement.setAttributeNS(null,"y",newy);
document.getElementById("firstGroup").appendChild(cloneElement);
}

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

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)

Comments