Cytoscape Tree Expand/Collapse

Using remove and restore

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.0.0/cytoscape.min.js"></script>
<h3>Click on nodes to expand and collapse the tree</h3>
<div id="cy"></div>

CSS

body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#cy {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
}

JavaScript

var elems = {
  nodes: [
    { data: { id: 'Start' } },
    { data: { id: '1' } },
    { data: { id: '2' } },
    { data: { id: '3' } },
    { data: { id: '4' } },
    { data: { id: '1A' } },
    { data: { id: '1B' } },
    { data: { id: '1C' } },
    { data: { id: '2A' } },
    { data: { id: '2B' } },
    { data: { id: '2C' } },
    { data: { id: '3A' } },
    { data: { id: '3B' } },
    { data: { id: '3C' } },
    { data: { id: '4A' } },
    { data: { id: '4B' } },
    { data: { id: '4C' } }
  ],
  edges: [
    { data: { source: 'Start', target: '1' } },
    { data: { source: 'Start', target: '2' } },
    { data: { source: 'Start', target: '3' } },
    { data: { source: 'Start', target: '4' } },
    { data: { source: '1', target: '1A' } },
    { data: { source: '1', target: '1B' } },
    { data: { source: '1', target: '1C' } },
    { data: { source: '2', target: '2A' } },
    { data: { source: '2', target: '2B' } },
    { data: { source: '2', target: '2C' } },
    { data: { source: '3', target: '3A' } },
    { data: { source: '3', target: '3B' } },
    { data: { source: '3', target: '3C' } },
    { data: { source: '4', target: '4A' } },
    { data: { source: '4', target: '4B' } },
    { data: { source: '4', target: '4C' } }
  ]
};

var childrenData = new Map(); //holds nodes' children info for restoration

var cy = cytoscape({
  container: document.getElementById('cy'),
  autounselectify: true,
  style: [
    {"selector":"core","style":
      {"selection-box-color":"#AAD8FF","selection-box-border-color":"#8BB0D0","selection-box-opacity":"0.5"}
    },
    {"selector":"node","style":
      {"width":"118px","height":"100px","content":"data(id)","font-size":"24px","text-valign":"center","text-halign":"center","background-color":"#555","text-outline-color":"#555","text-outline-width":"2px","color":"#fff","overlay-padding":"6px","z-index":"10"}
    },
    {"selector":"node[?attr]","style":
     ...