alexandernst alexandernst - 1 month ago 21
Javascript Question

Traversing jsTree tree

Example data:

1:A
2:Aa
3:Ab
4:Ac
5:Aaa
6:B
7:Ba
8:Bb
9:Baa
10:Bab


I'm trying to traverse a jsTree tree and get the path to each item, including parents and roots, so after finishing the traverse, I'd end up having this output:

[
10: ["/6/8/10", "Bab",
8: ["/6/8", "Bb",
5: ["/1/4/5", "Aaa"],
etc...
]


How can I do that?

Currently, I have this:

$('.jstree-node,.jstree-leaf').each(function(){
var id = ($(this).attr('id').split("_"))[0];
var text = $(this).children('a').text();
$('#textarea').append(id + " - " + text + "\n");
});


which gives me the ID and the text of each item, but


  • it feels ugly. My gut is telling me this can be done with jsTree's API

  • I'm not sure how to get the path of each item.


Answer

I found a solution:

$('.jstree-node,.jstree-leaf').each(function(){
    var id   = $(this).attr('id');
    var text = $(this).children('a').text();
    var path = tree.get_path( tree.get_node($(this)), "/", true);
    console.log( (id.split("_"))[0] + " - " + text + " -> (" + path + ")");
});