Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a specific parent using d3?

Tags:

d3.js

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.
like image 585
KingKongFrog Avatar asked Apr 28 '17 22:04

KingKongFrog


2 Answers

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>
like image 176
altocumulus Avatar answered Sep 28 '22 08:09

altocumulus


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()
like image 45
Eric Guan Avatar answered Sep 28 '22 07:09

Eric Guan