jstree jquery how to iterate through all nodes

Hshdj122 picture Hshdj122 · Jan 27, 2016 · Viewed 16k times · Source

I'm trying to iterate through every node within a treeview in jstree. The treeview is 4 levels deep but I can't seem to get past the 1st level. The following is the jQuery used to iterate.

$("#myTree").bind('ready.jstree', function (event, data) {
    $('#myTree li').each(function () {
        // Perform logic here
        }
    });
});

Here is a jsfiddle illustrating my point. Please help on how I can iterate through every node in jstree.

Answer

E. Sundin picture E. Sundin · Jan 27, 2016

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);
    });
});

JSFiddle - Docs for get_json