Reputation: 4189
It seems to me that there is no native function to ungroup an element in D3. So, I tried to remove the element from the group and thern recreate the element by append method, using this stackoverflow answer.
Unfortunately my code (fiddle) contains (at least) an error. I cannot understand what is.
[create four red circles, then change the color of the first one from red to green after having detached it from the group of all the circles]
var svg = d3.select('svg');
var dataSet = [10, 20, 30, 40];
var group=svg.append("g");
var circles = group.selectAll('circle')
.data(dataSet)
.enter()
.append('circle')
.attr("r",function(d){ return d })
.attr("cx",function(d, i){ return i * 100 + 50 })
.attr("cy",50)
.attr("fill",'red');
var circle=circles.select("circle");
var removed = circle.remove();
var newcircle=svg.append(function() {
return removed.node();
});
d3.select(newcircle).attr("fill","green");
Upvotes: 0
Views: 279
Reputation: 21578
There are two errors in your code:
You try to select a circle from the circles
selection. However, this would select a sub-element of the circles in that selection, which does not make any sense. Instead of
var circle = circles.select("circle");
you want
var circle = group.select("circle");
This way you select the circle from the group.
newCircle
already is a d3 selection object. It is an error re-select by doing d3.select(newcircle)
. The code should look like
newcircle.attr("fill", "green");
Putting this all together you end up with something as follows:
var svg = d3.select('svg');
var dataSet = [10, 20, 30, 40];
var group =svg.append("g");
var circles = group.selectAll('circle')
.data(dataSet)
.enter().append('circle')
.attr("r",function(d){ return d })
.attr("cx",function(d, i){ return i * 100 + 50 })
.attr("cy",50)
.attr("fill",'red');
var circle = group.select("circle");
var removed = circle.remove();
var newcircle = svg.append(function() {
return removed.node();
});
newcircle.attr("fill", "green");
<script src="https://d3js.org/d3.v5.js"></script>
<svg width="600" height="200"></svg>
Upvotes: 1