How do I select a specific parent using d3?
d3.js
Solution
The easiest way to find a parent element matching some selector string is by using the `Element.closest()` method:
Starting with the `Element` itself, the `closest()` method traverses parents (heading toward the document root) of the `Element` 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 (nodes[i]). 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>
Problem
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. ```