d3 indented tree close other nodes with child and open only specific node

449 views Asked by At

Hi i will use this jsfiddle as reference http://jsfiddle.net/Ge58Q/16/

 function expandSingle(d) {
  if (d._children) {
    d.children = d._children;
    d._children = null;
 }
}

as you can see i have a tree that has a multiple branch. What i want to do is onload i only want the NODE LIGHTNING has the child that open and that is the NODE TURBO. the NODES CUTE AND NODE TOXIC i want their child to be hidden. Is this possible to open only the specific node that i want?????????

i think it has something to do with the above code

1

There are 1 answers

1
user3714582 On BEST ANSWER

If you would like to expand the path from root to node with specific name, you could use some algorithm to get the path, e.g. depth-first with stack where you store the path. Here is the sample of function which encapsulates recursive function and returns the array with indexes of children positions from root to node:

function getPathToNode(val, rootNode) {
    var stack = [];
    var nodeFound = false;
    function getPathRec(node) {
        if (nodeFound) {
            return;
        }
        if (node._children || node.children) {
            var nodeChildren = node.children ? node.children : node._children;
            for (var i=0; i<nodeChildren.length; i++) {
                if (!nodeFound) {
                    stack.push(i);
                    getPathRec(nodeChildren[i]);
                }
            }
        }
        if  (node.name == val && !nodeFound) {
            nodeFound = true;
            return;
        } else if (!nodeFound) {
            stack.pop();
        }
    }
    getPathRec(rootNode);
    return stack;
}

Then you could expand the nodes on the path:

function expandToNode(val) {
    path = getPathToNode(val, flare);
    currentNode = flare;
    for (var i=0; i<path.length - 1; i++) {
        currentNode = currentNode.children[path[i]];
        expandSingle(currentNode);
    }
}

So simply call the function expandToNodes(val) with name of the node as val parameter:

expandToNode('turbo');

This is the working JSFiddle: http://jsfiddle.net/Ge58Q/18/

Limitations: if there were multiple nodes with exact name, it expands only the first found node. If you would like to expand all the routes, you could traverse whole root and return all of the paths. I tested the code only with your tree data so there could be some bugs.