Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data of parent node in d3.js

Tags:

d3.js

I am doing nesting in D3 and in a nested element, I need to reach data object on its parent.

Right now I am doing

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

Is there a better way?

like image 423
ahmet alp balkan Avatar asked Mar 14 '13 18:03

ahmet alp balkan


People also ask

How do I select parent nodes?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it. In HTML, the document is itself the parent node of html element.

What is the parent node?

A Node that is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.

What is datum in d3?

datum(data) will bind the entirety of data to every single element in the selection.

What is append in d3?

append() function is used to append a new element to the HTML tag name as given in the parameters to the end of the element. If the type that is given is a function then it must be evaluated for each element that is in the selection. Syntax: selection.


2 Answers

d3.select(this).node() is the same as just this in the context of a function passed to a D3 selection. You could rework it like this d3.select(this.parentNode).datum() and get the correct value back without having to use the ugly double-underscore property.

like image 153
mysterycommand Avatar answered Oct 04 '22 13:10

mysterycommand


The other method I'm familiar with is to use .each() on the parent, and then deal with children within the closure:

d3.selectAll('.parent').each(function(parentDatum) {     d3.select(this).selectAll('.child').each(function(childDatum) {         // do stuff with parentDatum and childDatum here     }); }); 
like image 31
nrabinowitz Avatar answered Oct 04 '22 13:10

nrabinowitz