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?
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)
}
});
});