javascript - Selections in D3, Jquery -
in answer mike posted here, overviews 3 different ways apply change matched element based on index or custom filter. i'm trying clarify, more people myself, actual selections in these solutions.
so given document 6 svg rects class .bar
, have these different selections , 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 here's get's more tricky (for me @ least), want apply style
3rd rectangle, rectangle can found using
d3.selectall(".bar")[0][2]
but if want use d3.selection.attr()
, returns
typeerror: property 'style' of object #<svgrectelement> not function
but can wrap selection
d3.select(d3.selectall(".bars rect")[0][2]).style("fill", "red")
and work expected.
then, if want apply filter, such
filter(function (d) { return d === 5 || d === 15;}
the d3.selectall(".bar")
must used, , d3.select(d3.selectall(".bar"))
not work correctly.
i've read mike's excellent tutorials , documentation on selections, when think have figured out, pops , surprises me. difference between these selections, , how know 1 use when? thank much, , sorry long post!
in general, shouldn't access elements of returned selection indices, rather filter or use subselection. way, can apply .attr()
, .atyle()
without problems. reason d3 doesn't return "pure" array of dom elements (like jquery does), elements in wrapper supports d3 operations. still behaves array though -- if index it, "pure" dom element. can give dom element d3.select()
, generate wrapper around element enables d3 stuff.
if have @ documentation filter()
, you'll find examples on how use , subselections. can use these techniques third element of selection example. using .filter()
function makes sense if have bound data objects you're filtering, otherwise subselection should want.
Comments
Post a Comment