In a response, Mike posted here , he considers three different ways to apply a change to a consistent item based on an index or a custom filter. I am trying to clarify, I hope, for more people than just me, the actual choice in these decisions.
Therefore, given the document with 6 SVG rectangles with the class .bar , we have these different options and what they return:
d3.select (". bar"):
[Array[1] 0: rect.[object SVGAnimatedString] length: 1 parentNode: html __proto__: Array[0]
d3.selectAll ("bar."):
[Array[6] 0: rect.[object SVGAnimatedString] 1: rect.[object SVGAnimatedString] 2: rect.[object SVGAnimatedString] 3: rect.[object SVGAnimatedString] 4: rect.[object SVGAnimatedString] 5: rect.[object SVGAnimatedString] length: 6 parentNode: html __proto__: Array[0]
$ ("bar."):
[ <rect class=β"dataBars" x=β"53.191489361702125" width=β"212.7659574468085" y="4.761904761904762" height=β"11.11111111111111">β</rect>β, <rect class=β"dataBars" x=β"74.46808510638297" width=β"372.3404255319149" y=β"20.634920634920636" height=β"11.11111111111111">β</rect>β, <rect class=β"dataBars" x=β"127.6595744680851" width=β"212.7659574468085" y=β"36.507936507936506" height=β"11.11111111111111">β</rect>,β <rect class=β"dataBars" x=β"31.914893617021274" width=β"212.7659574468085" y=β"52.38095238095238" height=β"11.11111111111111">β</rect>β, <rect class=β"dataBars" x=β"159.5744680851064" width=β"265.9574468085106" y=β"68.25396825396825" height=β"11.11111111111111">β</rect>β, <rect class=β"dataBars" x=β"234.04255319148936" width=β"138.29787234042553" y=β"84.12698412698413" height=β"11.11111111111111">β</rect>β, ]
Now that it gets more complicated (at least for me), let's say I want to apply style to the third rectangle, this rectangle can be found using
d3.selectAll(".bar")[0][2]
But if we want to use d3.selection.attr() , which returns
TypeError: Property 'style' of object
But we can wrap this choice
d3.select(d3.selectAll(".bars rect")[0][2]).style("fill", "red")
and it will work as expected.
Then, if we want to apply a filter, for example
filter(function (d) { return d === 5 || d === 15;}
you should use d3.selectAll(".bar") , and d3.select(d3.selectAll(".bar")) will not work.
I read Mike excellent tutorials and election documentation, but when I think I understand something pops up and it surprises me. So what is the difference between these choices and how can I find out which one to use? Thank you very much and sorry for the long post!