Skip to content Skip to sidebar Skip to footer

How Can I Get A List Of Tree-ancestors And Tree-descendants From This D3.js Layout.tree?

I'm experimenting with and modifying this example of d3.js to draw a tree based on a JSON tree structure. This is what part of the tree looks like to start out with: I'm trying to

Solution 1:

Each node should have a parent like this:

functioncollapse(d) {
    if (d.children) {
      d.children.forEach(function(child){
        child.parent = d;//so now each node will have a parent except root node.
      });      
      d._children = d.children;
      d._children.forEach(collapse);
      d.children = null;
    }
  }

Next a function to set the color. This function will iterate through the given node and set its children to have a color field.

functionsetColor(d, color) {
  d.color= color;
  if (d.children) {
    d.children.forEach(function(d){setColor(d,color)});
  } elseif(d._children){
    d._children.forEach(function(d){setColor(d,color)});
  }
}

On text click call this function:

functiontextClick(d) {
  setColor(root, "black");//set all the nodes to have black.
  d1 = d;
  //iterate over all its parent and make it redwhile(d1){
    d1.color = "red";
    d1 = d1.parent;
  }
  //set color of the children node to red.setColor(d, "red")
  update(root);//call update so that the node text color is colored accordingly.
}

working code here

Post a Comment for "How Can I Get A List Of Tree-ancestors And Tree-descendants From This D3.js Layout.tree?"