Andreas Zeiner Andreas Zeiner - 1 month ago 6
jQuery Question

Expand Tree to a specific level

How can I use

node.setExpanded(true);
to expand the tree only to a certain level?

What I mean is that I've got 6 depth-levels and only want 5 to be expanded -- the last one should be excluded.

Answer

This is just a guide, as you have provided no sample data or code, but you can use a recursive function to iterate the tree, stopping when a specific depth is reached. Something like:

function expandNode(node, depth) {
    // Expand this node
    node.setExpanded(true);
    // Reduce the depth count
    depth--;
    // If we need to go deeper
    if (depth > 0) {
        for (var i = 0; i < node.children.length; i++) {
            // Go recursive on child nodes
            expandNode(node.children[i], depth);
        }
    }
}

and call it with the root node and overall depth:

expandNode(rootNode, 5);

There may well be better methods to iterate a fancytree, but I have not used fancytree before