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

murze picture murze · Apr 6, 2010 · Viewed 79.6k times · Source

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

Answer

Brad picture Brad · Jul 13, 2011

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.