2

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 ?

Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • 1
    Apparently and unfortunately, nope. See my answer here: http://stackoverflow.com/questions/38233003/d3-js-v4-how-to-access-parent-groups-datum-index/38235820#38235820 – Gerardo Furtado Jul 27 '16 at 11:15
  • 1
    @GerardoFurtado Ha, thank you very much, I completely missed that question. Voting to close as a duplicate, then – nikoshr Jul 27 '16 at 11:19
  • I never really thought about this issue (I never needed the parent group index in my visualisations), but I believe that a workaround is possible... leave the question here and let's see if someone suggests something. – Gerardo Furtado Jul 27 '16 at 11:22

0 Answers0