Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the id of the selected node in jsTree?

How can I get the id of the selected node in a jsTree?

function createNewNode() {
  alert('test');
  var tree = $.tree.reference("#basic_html");
  selectedNodeId = xxxxxxxxx; //insert instruction to get id here
  tree.create({ data : "New Node Name" }, selectedNodeId);
}
like image 511
murze Avatar asked Apr 06 '10 14:04

murze


3 Answers

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.

like image 91
Brad Avatar answered Nov 17 '22 22:11

Brad


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');
like image 11
harpo Avatar answered Nov 17 '22 21:11

harpo


In jstree version 3.1.1, you can get it directly from get_selected:

$("#<your tree container's id>").jstree("get_selected")
like image 11
tipycalFlow Avatar answered Nov 17 '22 22:11

tipycalFlow