In http://bost.ocks.org/mike/selection/, Mike talks about applying functions on selections.
When you use a function to define a selection.attr or selection.style, the function is called for each element; the main difference with grouping is that the second argument to your function (i) is the within-group index rather than the within-selection index.
This might be simple, but for some reason, I can't completely understand this point. Would anyone be kind enough to explain this with an example.
the main difference with grouping is that the second argument to your function (i) is the within-group index rather than the within-selection index.
Remember the index passed in to any attr, style, etc. functions in d3?
...
.attr('something', function(d, index) {
// major gymnastics with d and index
}
So when you do a selectAll, the index starts from 0 for each group.
So, if you do two chained selectAlls where the first (group) levels are rows (tr) and the second (child) levels are cells (td), you'd have the following passed in as indices for a 2 rows x 3 cells table
0, 1, 2, 0, 1, 2
instead of
0, 1, 3, 4, 5, 6
which is what you'd expect when you select just 6 nodes with a single selectAll.
The following snippet of code illustrates this
d3.selectAll("#a tr").selectAll("td").text(function(d, index) {
return index;
})
d3.selectAll("#b td").text(function(d, index) {
return index;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Grouped cells (i.e. 2 selectAll)
<table id="a">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Ungrouped cells (i.e. 1 selectAll)
<table id="b">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
The first animation on the page you linked to (http://bost.ocks.org/mike/selection/) illustrates this pretty well - here's a marked up version of the same
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