I have a jstree. I want to select the node which is bound to the object which has a location with id of 158. This works but seems stupid. What\'s the more idiomatic way of doing
i use jstree 3.0.8. don't use 'state'
'plugins' : ['dnd','sort','types','contextmenu','wholerow','ui']
and server offer the json, the selected node has
"state":{"selected":true,"opened":true}
Just wanted to chime in here as none of the answers worked for me. What finally DID work was very simple:
$('#someTree').jstree('select_node', 'someNodeId');
Note that I didn't initialize someNodeId
as a jQuery object. It's just a plain string.
I did this right after a tree was loaded without putting it into a "ready" bind event as it seems to not be necessary.
Hope it saves some one from a few frustrating hours. . .
To hook into the tree after it has been loaded:
.on('loaded.jstree', function() {
// Do something here...
});
Based on jsTree groups you can try
jQuery("#getStartedTree").jstree("select_node", "#test2");
if the data looks like
The JSON in the TextFile.txt - borrowed from your simple example
[
{
"data" : "A node",
"children" : [ "Child 1", "Child 2" ]
},
{
"attr" : { "id" : "test1" },
"data" : {
"title" : "Long format demo",
"attr" : { "id" : "test2", "href" : "#" }
}
}
]
and jsTree set up
My tree container is <div id="getStartedTree">
My jsTree code
$("#getStartedTree").jstree({
"themes": {
"theme": "default",
"url": "../App_Css/Themes/Default/style.css",
"dots": true,
"icons": true
},
"json_data": {
"ajax": {
"url": "../SiteMaps/TextFile.txt",
"dataType": "json",
"data": function(n) {
return { id: n.attr ? n.attr("id") : 0 };
}
}
},
"plugins": ["themes", "json_data", "ui"]
});
Is that what you are after?
This solution Works for me
// after the tree is loaded
$(".jstree").on("loaded.jstree", function(){
// don't use "#" for ID
$('.jstree').jstree(true).select_node('ElementId');
});
and even in a php loop (dynamically) :
$(".jstree").on("loaded.jstree", function(){
<?php foreach($tree as $node): ?>
$('.jstree').jstree(true).select_node('<?=$node?>');
<?php endforeach;?>
});
Hope this works for you.
If you're populating the tree using HTML instead of JSON data and wondering how to set the node_id
, you just need to set the id attribute of the <li>
element!
<div class="tree-menu">
<ul class="menu">
<li id="node_1">
Node 1 - Level 1
<ul class="menu">
<li id="node_3">
Node 3 - Level 2
</li>
</ul>
</li>
<li id="node_2">
Node 2 - Level 1
</li>
</ul>
</div>
Then
$('.tree-menu')
.jstree(true)
.select_node("node_3");
will select the Node 3 - Level 2
node.
For those getting javascript errors, remember to use Full version of jQuery
, not the slim version!
For all down voters, here is the demo to prove it's working: https://jsfiddle.net/davidliang2008/75v3fLbs/7/
trigger click on first anchor
$("#jstree .jstree-anchor:first").click();
or by node id 158
$("#jstree #158").find(".jstree-anchor:first").click();
$('#' + 158).find(".jstree-anchor:first").click();