I am trying to change the style of some svg element. when I do this:
var circleSelected = d3.select("#circleid_2");
circleSelected.style("fill", "purple");
circleSelected.style("stroke-width", 5);
circleSelected.style("stroke", "red");
the circle is changing its style.
BUT, when i do this:
var allCircles = d3.selectAll(".circle");
allCircles.forEach(function (circle) {
circle.style("fill", "green"); //function(d) { return getNodeColor(d); }
});
it does not work with the error: Object [object SVGCircleElement] has no method 'style'
and here is my 'circle' declaration (note: it has both class and id):
node.append("circle")
.attr("id", function (d) { return "circleid_" + d.id; })
.attr("class", "circle")
.attr("cx", function (d) { return 0; })
.attr("cy", function (d) { return 0; })
.attr("r", function (d) { return getNodeSize(d); })
.style("fill", function (d) { return getNodeColor(d); })
.style("stroke", function (d) { return getNodeStrokeColor(d); })
.style("stroke-width", function (d) { return getNodeStrokeWidth(d); });
What am I doing wrong here? Thanks for the help!
Try:
d3.selectAll("circle").style("fill", "green");
Or:
allCircles.style("fill", "PaleGoldenRod");
Explanation: d3.selectAll
will return a selection, which can be acted upon using the functions described in this API: https://github.com/d3/d3/blob/master/API.md#selections-d3-selection
However, as soon as you do forEach
, the internal variable returned each time as circle
will be an actual DOM element - no longer a selection, and therefore no style
function attached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With