Getting parent attributes from children in nested selections?

2,094 views
Skip to first unread message

Ed

unread,
Sep 20, 2012, 7:00:51 PM9/20/12
to d3...@googlegroups.com
I have a stacked barchart that I produced with a nested selection/d3.nest datastructure and was wondering what the best idiom for
getting information about the parent (in this case the parent's index) from the child was. I'm using the following, which seems to work:

in the parent:

.attr( "data-idx", function( d, i ) { return( i ); } )

in the child which is nested inside two <g>'s:

var idx = +d3.select( this.parentNode.parentNode ).attr( "data-idx" );

Is this considered good form or is there a better way to do it?

Chris Viau

unread,
Sep 21, 2012, 1:40:24 PM9/21/12
to d3...@googlegroups.com
You can grab the parent index from a third argument in the accessor function: function(d, i, j){ /* j is the parent index */ };
Here I show 3 of the multiple ways of accessing parents data and index: http://jsfiddle.net/christopheviau/dHtMj/
Chris

Ed

unread,
Sep 25, 2012, 4:14:12 PM9/25/12
to d3...@googlegroups.com
So simple, thanks!

  - Ed

Paulo Brito

unread,
Dec 6, 2012, 10:19:44 PM12/6/12
to d3...@googlegroups.com
Hi, if I add a transition j returns undefined, is that the normal behavior?

.append("text").transition()
    .duration(2000)
    .attr({class'value'xcellXdy'1em'})
    .text(function(dij){
        console.log('Method A: Parent data: 'data[j]'Parent index: 'j);
        console.log('Method B: Parent data: 'this.parentNode.__data__);                                  
        return d;
     });
Thanks,
Paulo Brito

Chris Viau

unread,
Dec 6, 2012, 10:28:58 PM12/6/12
to d3...@googlegroups.com
The j will probably only be available if you have a subselection. Can you share the rest of your code on bl.ocks, tributary or jsfiddle?

Paulo Brito

unread,
Dec 6, 2012, 10:40:44 PM12/6/12
to d3...@googlegroups.com
I made the changes to your code 
http://jsfiddle.net/paulosb/GcXrJ/

Chris Viau

unread,
Dec 7, 2012, 4:44:36 AM12/7/12
to d3...@googlegroups.com
Interesting
Reply all
Reply to author
Forward
0 new messages