Nikunj Aggarwal Nikunj Aggarwal - 5 months ago 32
Javascript Question

duplicating the whole svg element using d3.js

I am creating a

, inside that rectangle i am creating 10 smaller rectangles`.

i want to replicate whole thing into another svg element on mouse click.

link of the code :

Here is the code:

var svgContainer ="body").append("svg")
.attr("width", 200)
.attr("height", 200);

//Draw the Rectangle
var rectangle = svgContainer.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("fill", "red")
.attr("width", 200)
.attr("height", 200);

var bigRectContainer ='#bigRectContainer').append('svg')
.attr('width', 200)
.attr('height', 200);
var dim = 20;
var x = 0;
var y = 0;
for (i = 1; i < 11; i++) {

x = 10 + (i-1)*dim;
y = 10;

.attr("x", x)
.attr("y", y)
.attr("width", 20)
.attr("height", 20)
.style("fill", "black");

var bigRectContainer = svgContainer.append("g");
svgContainer.selectAll("rect").on("click", function () {
var littleRect =;

var bigRect = bigRectContainer.selectAll("rect")


Please tell me where i made the mistake...


I'm not entirely certain what you're trying to do with the code you've posted, but I thought that duplicating an entire SVG node was interesting. It turns out it's quite easy to do with selection#html - this doesn't work on the SVG node, but it does work on its container, so it's easy to clone the whole node:

function addAnother() {
    var content =;
    var div ='body').append('div')
    div.selectAll('svg').on('click', addAnother);

svg.on('click', addAnother);

See working fiddle here. Note that this only works if the SVG node is the only child of its parent - otherwise, you might need to wrap it somehow.