Prior to D3 4.0, the functions passed to the modification methods received the index of the parent element as third argument.
For example, to display a b c d
in a square, I could do
var data = [
['a', 'b'],
['c', 'd']
];
var n1 = d3.select('svg').selectAll('g').data(data)
.enter().append('g');
n1.selectAll('text').data(function(d) { return d; })
.enter().append('text')
.attr('x', function(d, i) {
return i*50;
})
.attr('y', function(d, i, parentIx) {
return parentIx*50 + 10;
})
.text(function (d) {
return d;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg style='width:100px; height:100px'></svg>
In 4.0, the third argument is now the current group (nodes). Pointing D3 to a 4.0 source obviously breaks the y
attribute:
var data = [
['a', 'b'],
['c', 'd']
];
var n1 = d3.select('svg').selectAll('g').data(data)
.enter().append('g');
n1.selectAll('text').data(function(d) { return d; })
.enter().append('text')
.attr('x', function(d, i) {
return i*50;
})
.attr('y', function(d, i, parentIx) {
return parentIx*50 + 10;
})
.text(function (d) {
return d;
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg style='width:100px; height:100px'></svg>
Is there a way to determine the index of the parent element, besides navigating the DOM and calculating the index ?