I'm using jstree and I want to delete a specific node by its ID after a click on a button.
This is my tree in html list format:
<div id="testtree">
<ul>
<li id="1" title="ID:1"><a>Fruits and Vegetables</a>
<ul>
<li id="11" title="ID:11"><a>Fruit</a>
<ul>
<li id="111" title="ID:111"><a>Apple</a></li>
<li id="112" title="ID:112"><a>Banana</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
and this is my button event (I've got several buttons, hence the array):
buttons[0].addEventListener( "click", function( ev ) {
$("#testtree").jstree("remove", $("111"));
});
Any ideas what I'm missing?
Update:
I've corrected the typo but it still doesn't work. Here's the complete code, maybe the mistake is somewhere else?
<html>
<head>
<title>jstree test</title>
</head>
<body>
<div id="testtree">
<ul>
<li id="1" title="ID:1"><a>Fruits and Vegetables</a>
<ul>
<li id="11" title="ID:11"><a>Fruit</a>
<ul>
<li id="111" title="ID:111"><a>Apple</a></li>
<li id="112" title="ID:112"><a>Banana</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<button>Remove Apple</button>
<script type="text/javascript" src="_lib/jquery.js"></script>
<script type="text/javascript" src="jquery.jstree.js"></script>
<script>
$(document).ready(function() {
$("#testtree").jstree({
"plugins" : [ "themes", "html_data", "checkbox", "ui" ],
"core": { "initially_open": ["1"]}
});
});
var buttons = document.querySelectorAll("button");
buttons[0].addEventListener( "click", function( ev ) {
$("#testtree").jstree("remove","#111");
});
</script>
</body>
</html>
Any of the answers worked for me. I prefer to use that instead:
$.jstree._reference("#tree-container or node or jquery selector").delete_node(node);
Hope it helps someone.
jsTree's manual (ver 3.0.0) says:
Please keep in mind that by default all modifications to the tree are prevented (create, rename, move, delete). To enable them set core.check_callback to true
You can also use function to specify the type of modification to allow. For example, to allow only node removing:
$('#tree').jstree({
'core' : {
'check_callback' : function (operation, node, node_parent, node_position, more) {
// operation can be 'create_node', 'rename_node', 'delete_node', 'move_node' or 'copy_node'
// in case of 'rename_node' node_position is filled with the new node name
return operation === 'delete_node';
}
}
});
According to jsTree documentation you remove like this
$("#testtree").jstree("remove","#111");
Without $()
$("#testtree").jstree({
"plugins": ["themes", "html_data", "checkbox", "ui", "crrm"],
"core": {
"initially_open": ["1"]
}
});
You need to add "crrm" to plugins
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With