I'd like to select the parent node which may be a few levels higher. How do I do that with d3?
<div class="parent">
<div class="stepson">
<div class="child">
Wassup Fatso?
</div>
</div>
</div>
d3.select('.child').parent('.parent')....? //I would like to go up the dom to a element with class parent.
The easiest way to find a parent element matching some selector string is by using the Element.closest()
method:
Starting with the
Element
itself, theclosest()
method traverses parents (heading toward the document root) of theElement
until it finds a node that matches the provided selectorString.
To keep it within the D3 universe, you can make use of the selection.select()
method, which accepts a selector funtion as its argument:
If the selector is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodeson-topic). It must return an element, or null if there is no matching element.
Calling this method on the child's selection you are getting access to the child's DOM element which is referred to by this
. From there on you can easily find the parent element you are after:
const parent = child.select(function() {
return this.closest(".parent"); // Get the closest parent matching the selector string.
});
Have a look at the following snippet for an executable demo:
const child = d3.select(".child"); // Select the child.
const parent = child.select(function() {
return this.closest(".parent"); // Get the closest parent matching the selector string.
});
console.log(parent.node()); // <div class="parent">…</div>
<script src="https://d3js.org/d3.v5.js"></script>
<div class="parent">
<div class="stepson">
<div class="child">
Wassup Fatso?
</div>
</div>
</div>
I don't think D3 provides this jQuery like selector. You can probably do it through native dom selectors.
var parent = d3.select('.child').node().parentNode.parentNode
Then you can retrieve the data for this node like so
d3.select(parent).datum()
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