0

This is the code sample that I am using in reactjs.

const node = graph.$(`#${selectedNode.id()}`);
      graph.remove(node);

selectedNode.id is the id of the parent node but it deletes all the children nodes inside this parent node. How can I delete the parent node only and not its descendants?

This question is similar to this on here Remove/hide compound node without removing/hiding descendants but I will appreciate it if some code samples are provided because in the doc here http://js.cytoscape.org/#collection/graph-manipulation/eles.move we have a shallow code example of edges but I am interested in nodes.

Thanks

joseluke
  • 65
  • 1
  • 12

1 Answers1

4

You can delete a parent node by first moving its children to the parent's parent (if it exist, otherwise you should assig a null value) and then removing the parent node. Select a parent node and click on the delete button in the below example.

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  layout: {name: 'grid', rows: 2},
  style: [{
      selector: 'node',
      css: {
        'label': 'data(id)'     
        }
    }
  ],
  elements: {
    nodes: [{
        data: {
          id: 'n0',
          parent: 'n1'
        }
      },
      {
        data: {
          id: 'n1',
          parent: 'n2'
        }
      },
      {
        data: {
          id: 'n2'
        }
      },
      {
        data: {
          id: 'n3'
        }
      }
    ],
    edges: [
      {
        data: {
          id: 'n2n3',        
          source: 'n2',
          target: 'n3',
          weight: 7
        }
      }
    ]
  }
});

document.getElementById("deleteButton").addEventListener("click", function() {
  let selected = cy.nodes(':selected')[0];
  selected.children().move({parent : (selected.parent().id() ? selected.parent().id() : null)});
  selected.remove();
});
body {
  font: 14px helvetica neue, helvetica, arial, sans-serif;
}

#button {
  z-index = 1000;
}

#cy {
  height: 95%;
  width: 95%;
  left: 0;
  top: 50;
  z-index = 900;
  position: absolute;
}
<html>

<head>
  <meta charset=utf-8 />
  <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
  <script src="https://unpkg.com/cytoscape@3.10.0/dist/cytoscape.min.js">
  </script>
</head>

<body>
  <button id="deleteButton" type="button">Delete selected</button>
  <div id="cy"></div>
</body>

</html>
Hasan Balcı
  • 938
  • 7
  • 13