Accepted answer

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.


D3 doesn't provide cloning functionality, probably because of the native cloneNode method that already exists on DOM elements, including SVG nodes.

This method includes a boolean parameter to deep copy (i.e. copy all descendants) instead of just cloning the node it is called on. You would probably want to do something like bigRectContainer.node().cloneNode(true) to copy the entire DOM branch of rectangles.

Related Query

More Query from same tag