jstree jquery how to iterate through all nodes
This gets all the children of your tree in a flat array for your .each
loop.
$("#tree").bind('ready.jstree', function(event, data) { var $tree = $(this); $($tree.jstree().get_json($tree, { flat: true })) .each(function(index, value) { var node = $("#tree").jstree().get_node(this.id); var lvl = node.parents.length; var idx = index; console.log('node index = ' + idx + ' level = ' + lvl); });});
Another way is to open them before trying to access nodes in dom and then close them:
$("#tree").bind('ready.jstree', function (event, data) { $(this).jstree().open_all(); // open all nodes so they are visible in dom $('#tree li').each(function (index,value) { var node = $("#tree").jstree().get_node(this.id); var lvl = node.parents.length; var idx = index; console.log('node index = ' + idx + ' level = ' + lvl); }); $(this).jstree().close_all(); // close all again});
"Nodes" is an overloaded term. Do you mean the HTML nodes or just the JSON data used to define each node in the jstree? I had a need to iterate through the jstree in order to extract the value for the ID field in each jstree node. If that's all you need, there's a simpler approach:
var v =$("#tree").jstree(true).get_json('#', {'flat': true});for (i = 0; i < v.length && i < 10; i++) { var z = v[i]; alert("z[id] = " + z["id"]);}