Javascript – jsTree: how to select node after refresh

javascriptjqueryjstree

I have a jQuery jsTree populated from the server via an ajax call. When I add a new node I make an ajax call then make a call to refresh the tree with tree.jstree("refresh"). After the refresh I want to select the node I just added. Unfortunately there doesn't seem to be a callback that can be passed to this command. Is there any clean way to do this?

Best Answer

oh, such a long time since this post ... and still couldn't find an answer on internet. So after a few hours of ... no no no, not this, came up with a solutin

var jsTreeId = '#jstree'; // or whatever name the jstree has
var jsTreeSelectedItemId = 5; // just an example
var selectedNode = $('#node_'+jsTreeSelectedItemId);
var parentNode = $.jstree._reference(jsTreeId)._get_parent(selectedNode);

// now lets say that you add a new node from server side, you get the new id of the created node by an ajax call, and next you want to refresh the tree in order to display it, and also select it

var newSelectId = 9; // or from ajax call
// call the refresh function, which is asnyc
$.jstree._reference(jsTreeId).refresh(parentNode); 
 // set the magic "to_select" variable with an array of node ids to be selected
// note: this must be set after refresh is called, otherwise won't work
$.jstree._reference(jsTreeId).data.ui.to_select = ['#node_'+newSelectId];