How do I get the id of the selected node in jsTree?
Unable to get harpo's solution to work, and unwilling to use Olivier's solution as it uses internal jsTree functions, I came up with a different approach.
$('#tree').jstree('get_selected').attr('id')
It's that simple. The get_selected
function returns an array of selected list items. If you do .attr
on that array, jQuery will look at the first item in the list. If you need IDs of multiple selections, then treat it as an array instead.
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');
In jstree
version 3.1.1
, you can get it directly from get_selected
:
$("#<your tree container's id>").jstree("get_selected")