Can I move an SVG element between SVG groups, in d3.js
d3.js, svg
Solution
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.
Problem
Can I move an SVG element between SVG groups - without stirring too much calculation behind the scenes nor crafting too much code in my own code? The d3 api documentation mentions you cannot re-append removed elements (?). Recreating the element after removing it from its original group - may seem to be cumbersome in my code, and more expensive for d3 and the browser than it could be if that were possible. This is also relevant for defining an element before associating it with a group, not just for really moving it between groups (i.e. for moving an element from a non-group to a group).