How to remove a node on a D3.js tree structure?

I am new to D3.js. I am trying to remove a node from a tree layout, but I could not find a way to do this. This is a sample tree template.
https://dl.dropbox.com/u/7098/tree/dynamic3.html

I want to delete like this dynamically:
https://dl.dropbox.com/u/7098/tree/aaa.gif

I believe that I need to perform some operation for root json object ...
If you have an idea, let me know.

+4
source share
2 answers

this makes an explicit seb answer. where you set up the click handler, put this:

.on("click", function(d) { if (d.parent && d.parent.children){ console.log('removing ' + d.name); var nodeToDelete = _.where(d.parent.children, {name: d.name}); if (nodeToDelete){ d.parent.children = _.without(d.parent.children, nodeToDelete[0]); } } }); 

which should get what you want. be sure to call any method that draws a tree from the source data, which is now modified. note: I use the underscore library to use _.where and _.without, although you could do it with pure js or with another library. some of the checks are for convenience and to prevent root node removal, for example.

ps since you probably want to keep your expand / collapse behavior, then just put the conditional expression in the callback to check the modifier key to indicate the removal of the node using, for example, d3.event.altKey.

+2
source

The principles that you need to follow are answered in Collapse / expand child nodes of the tree in d3.js? . This example shows how to collapse the tree in the click handler for node.

If you change the data structure that you passed to the layout manager, then the tree will be updated accordingly. If you collapse the tree layout in the above example, you remove the node children attribute: the children value is hidden in the _children variable _children that the children can switch again. See the toggle function for details.

To remove a node, follow the same logic, but remove the node that receives the click event from its parent list of children . To find a parent, you can either go through the tree in the click handler or save a link to each parent in the data structure.

0
source

All Articles