How do I select a specific parent using d3?

I would like to select the parent node, which can be several levels higher. How do I do this 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.

      

+3


source to share


2 answers


As Gerardo Furtado pointed out in his comment , the best way to achieve this would be to walk up the DOM tree until the element having a class parent

. To keep it in the D3 universe, you can use a method selection.select()

that takes a select function as an argument:

If the selector is a function, it is evaluated for each selected element to pass the current date (d), the current index (i), and the current group (s) as the current DOM Element (nodes [i]). It should return an element or null if no matching element exists.

By calling this when a child is selected, you are accessing the child DOM with this

. From there, you can traverse the DOM upwards by reading the property .parentElement

.



The implementation can be done in the following lines:

var child = d3.select(".child");                // Select the child

var parent = child.select(function() {
  var element = this;                           // this points to the child element
  while (!d3.select(element).classed("parent")) // while no class "parent" was found...
    element = element.parentElement;            // ...walk up one level
  return element;                               // return the parent element
});

console.log(parent);                            // <div class="parent">…</div>
      

<script src="https://d3js.org/d3.v4.js"></script>

<div class="parent">
   <div class="stepson">
       <div class="child">
            Wassup Fatso?
       </div>
   </div>
</div>
      

Run code


+2


source


I don't think D3 provides this jQuery as a selector. You can probably do this with dom selectors.

var parent = d3.select('.child').node().parentNode.parentNode

      



Then you can get data for that node like this

d3.select(parent).datum()

      

0


source







All Articles