How can I get the id of the selected node in a jsTree?
function createNewNode() {
alert(\'test\');
var tree = $.tree.reference(\"#basic_html\");
select
In jstree
version 3.1.1
, you can get it directly from get_selected
:
$("#<your tree container's id>").jstree("get_selected")
$.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
id = $(this).attr("id");
alert('Id selected: ' + id);
});
With latest version of Jstree; you can do it as following:
<script type="text/javascript>
var checked_ids = [];
$('#your-tree-id).jstree("get_checked",null,true).each(function(){
checked_ids.push(this.id);
});
alert(checked_ids.join(","));
</script>
Nodes in jsTree are essentially wrapped list items. This will get you a reference to the first one.
var n = $.tree.focused().get_node('li:eq(0)')
You can replace $.tree.focused()
if you have a reference to the tree.
To get the id, take the first matched element
if (n.length)
id = n[0].id
or you can use the jQuery attr function, which works on the first element in the set
id = n.attr('id');
<script type="text/javascript>
checked_ids.push($(this).context.id);
</script>
In some cases and/or jstree versions this solution doesn't work.
$('#tree').jstree('get_selected').attr('id');
Instead of defined "id" I get nothing. What did the trick for me is:
$("#tree").jstree("get_selected").toString();