PlotTwist
PlotTwist

Reputation: 27

How can I check if a node is a parent in jstree after I've clicked a button?

I'm creating a button to delete nodes after I selected them. I want to make it able to only delete child nodes. In order to do it, I need to check if the node is a parent or not.

So code would look something like

$(".delete-node").click(function() {
    // gets the selected nodes
    $('#jstree1').jstree(true).get_selected(); 

    if (data.instance.is_leaf) { 
        //My problem is HERE. Only delete if all nodes are children/not parent
        //here I delete the nodes selected
        $('#jstree1').jstree(true)
                     .delete_node($('#jstree1')
                     .jstree(true)
                     .get_selected()); 
    }
});         

I know this is simple but I can't seem to put it to work. I'm kinda new to jQuery and JavaScript so what am I missing?

Upvotes: 2

Views: 2789

Answers (2)

Nikolay Ermakov
Nikolay Ermakov

Reputation: 5061

You will need to get the node by the id and then check if it is a parent. See code like below. Check demo - Codepen Demo

$('#jstree1')
  .jstree({
    core: {
      data: treeData,
      check_callback: true  // don't forget to set this param to true
    }
  });

$(".delete-node").click(function() {
  var tree = $('#jstree1').jstree();
  // gets the selected nodes
  var selectedNodeIds = tree.get_selected();
  selectedNodeIds.forEach(function(nodeId) {
    var node = tree.get_node(nodeId);
    if (!tree.is_parent(node)) {
      tree.delete_node(node)
    }
  });
});

Upvotes: 2

gauravmuk
gauravmuk

Reputation: 1616

You can do $(element).children().length === 0 meaning it has no child nodes.

To delete all the child nodes in such case $(element).children().remove() will remove all the child nodes.

Upvotes: 0

Related Questions