score:0

you can't do this in d3, but jquery has the .appendto() function for that, e.g.

$("#element").appendto("#othergroup");

score:0

perhaps you could do this, with multiple elements:

d3.select('#btn').on('click', function() {
  circle.remove()
    .each(function(){
    group2.node().appendchild(d3.select(this).node());
  });
});

jsfiddle

score:4

to just move around existing nodes within the dom tree it is not necessary to first remove them to later re-append those same nodes at a different position. d3.append() internally uses node.appendchild() which works as follows:

if the given child is a reference to an existing node in the document, appendchild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

this means that a node can't be in two points of the document simultaneously. so if the node already has a parent, the node is first removed, then appended at the new position.

as other answerers have already mentioned both selection.append() and selection.insert() when being passed a function will append or insert, respectively, the node returned by that function. knowing that, all it takes to move around a dom node from its current position to a new target is

target.append(() => existingnode);  // target is a d3 selection, existingnode is a native dom node

having this in your toolbox it is also fairly easy to move around multiple nodes at once:

selectiontobemoved.each(function() { target.append(() => this); });

have a look at the following demo to see it in action. the two circles colored in aquamarine are move from group #g1 to group #g2.

const current = d3.select("#g1");
const target  = d3.select("#g2");

current.selectall("circle[fill=aquamarine]")
  .each(function() { target.append(() => this); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.0/d3.min.js"></script>

<svg>
  <g id="g1">
    <circle cx="100" cy="100" r="20" fill="aquamarine" />
    <circle cx="150" cy="100" r="20" fill="hotpink" />
    <circle cx="200" cy="100" r="20" fill="aquamarine" />
  </g>
  <g id="g2">
  </g>
</svg>

score:17

the docs you posted also mention that you can re-add the elements by passing a function to .append or .insert. here's what it says:

note that there is not currently a dedicated api to add removed elements back to the document; however, you can pass a function to selection.append or selection.insert to re-add elements.


since using .remove on a selection returns that selection, you could store the removed element in a variable, and then .append it to the new group using selection.node() to grab the dom element from the removed selection:

var removed = yourselection.remove();
yourtargetgroup.append(function() {
  return removed.node();
});

here's a simple fiddle that uses this technique to move a circle element from one group to another in a click handler.


Related Query

More Query from same tag