frazman
frazman

Reputation: 33223

get the parent nodes to a given node in d3 dendogram

I am a beginner in javascript/flask and I am trying to experiment with this d3 dendogram example: https://bl.ocks.org/mbostock/4063570

What I am trying to get is, when a node is clicked, return the parent nodes to the flask app server.

For example: If i click on display node, then server gets "flare,display"

if cluster node is clicked, then server gets "flare,analytics,cluster"

Upvotes: 3

Views: 176

Answers (2)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

It's very simple to get the parents of the clicked node. Just use ancestors(), which:

Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root.

So, in your case...

node.on("click", function(d){
    console.log(d.ancestors())
});

.. will show all the ancestors in the console, as an array.

Here is the forked bl.ocks: https://bl.ocks.org/anonymous/e36d4af364642a70818987941aa192c8/c75e620e662a6899d8df34c287fc5ea00d049513

In that code I'm mapping the array to get the id property of each node.

Upvotes: 2

Cyril Cherian
Cyril Cherian

Reputation: 32327

You can recurse over the clicked data:

var node = g.selectAll(".node")
      .data(root.descendants())
    .enter().append("g")
      .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      //attach a click listener to the group
      .on("click", function(d){
        var children = [];
        //recursively call parent
        var recurse = function(c){
          //recurse unless no parent is found
          if (c.parent){
            children.push(c.parent.id);
            recurse(c.parent)
          }
        }
        recurse(d)//call recurse on clicked node
        console.log(children)
        //send children to server via AJAX
      })

working example here

Upvotes: 1

Related Questions