D3.js Tree Expand All and Collapse All

d3.js, javascript

Solution

Try this code. Here is the working JsFiddle.

function expand(d){   
    if (d._children) {        
        d.children = d._children;
        d._children = null;       
    }
    var children = (d.children)?d.children:d._children;
    if(children)
      children.forEach(expand);
}
    
function expandAll(){
    expand(root); 
    update(root);
}
    
function collapseAll(){
    root.children.forEach(collapse);
    collapse(root);
    update(root);
}

Problem

I'm building a Tree using D3.js and what I am trying to do is add two buttons, Expand All and Collapse All to the top of the page like this. When I click "Expand All", all the nodes should expand. And when I click "Collapse All", all the nodes should collapse to the root element. Here's my current code http://bl.ocks.org/anonymous/ab8d7f85cca6f745a107 But the problem is, it isn't working. Can somebody suggest how to make it work?

Original source