How to get parent node data in d3.js

I am involved in nesting in D3 and in a nested element, I need to get the data object in its parent.

I'm doing now

d3.select(this).node().parentNode.__data__; 

Is there a better way?

+42
Mar 14 '13 at 18:28
source share
3 answers

d3.select(this).node() matches just this in the context of the function passed to the D3 fetch. You can redo it like this: d3.select(this.parentNode).datum() and return the correct value without using the ugly double underscore property.

+59
Jul 03 '13 at 23:30
source share

Another way I'm familiar with is using .each() for the parent, and then handling the children in a closure:

 d3.selectAll('.parent').each(function(parentDatum) { d3.select(this).selectAll('.child').each(function(childDatum) { // do stuff with parentDatum and childDatum here }); }); 
+16
Mar 14 '13 at 21:16
source share

I found this post when I had exactly the same problem. My solution was to change the selection to pass the data that I would need in a child, which in my opinion can be valid if you can live with data redundancy in node.

 [ { title: "Google", link: "www.google.com", languagePath : "en,fr,it" }, ... ] 

To help explain, I used this in the context of a two-column table. The first column has a title , and the second column has a for each of the accept-language elements.

So, I made subselections of the split languagePath and for every call to enter I would create a with the text being the language.

So, at this point, I will also need a link , so the elements of a look like this:

 <a href="www.google.com/en">EN</a> <a href="www.google.com/fr">FR</a> 

But link not part of the data passed to this child, so when I made a choice, and did not:

 var langLinks = tableRow .append("td") .selectAll("span") .data(function(d) { return d.languagePath.split(",") }) 

I did

  var langLinks = tableRow .append("td") .selectAll("span") .data(function(d) { return d.languagePath.split(",").map(function(item) { return { lang : item, link : d.link }) }) 

So, when I process the data in enter() this choice, I have parent data.

Hope this is a suitable alternative for some of you, it helped me.

+6
Apr 16 '14 at 16:26
source share



All Articles