score:1

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()

score:5

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 (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>


Related Query