Search code examples
javascriptjqueryjstree

jstree: Select a node in jstree by name attribute rather than id


I need to select a node in the jstree by it's attribute name. Then after selecting that node I need to get it's id. Basically I want to get the id of a node given its name.

I tried the following code:

$("#tree1").bind("loaded.jstree", function (e, data) {

var isa_name = "ISA16469";

//$("#tree1").jstree("select_node", "#01"); //this code works but it selects by id, I want to select by attribute name

$("#tree1").jstree("select_node", $("li[name='" + isa_name + "']")); //doesn't work

var test = $('#tree1').jstree('get_selected').attr('id'); //get id of selected node
alert(test)

})

Your help is most welcome. Thanks a lot


Solution

  • When using an ID as selector (in jstree functions), do not supply a leading #, use the ID only.

    As for the question - unfortunately that will not work, since jstree only keeps visible nodes in the DOM, meaning that if your LI node is not revealed (for example if its parent is closed) you will not be able to find it in the DOM.

    I am not sure that having a name attribute on a LI node is valid, but anyway - if you insist on finding the node this way, you will have to traverse the internal jstree model. Here is how you do it: http://jsfiddle.net/DGAF4/450/