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?
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.
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.
datum(data) will bind the entirety of data to every single element in the selection.
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.
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.
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 }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With