How to count total number of leaf nodes from Jstree Data Model?

3,909 views
Skip to first unread message

Tree Rocker

unread,
Mar 4, 2014, 11:59:29 PM3/4/14
to jst...@googlegroups.com
Is there any way to calculate total number of leaf nodes from the Jstree Model not from DOM?

Ivan Bozhanov

unread,
Mar 5, 2014, 2:35:40 AM3/5/14
to jst...@googlegroups.com
Use:
instance.get_json('#', { "flat" : true }).length

Tree Rocker

unread,
Mar 5, 2014, 4:49:53 AM3/5/14
to jst...@googlegroups.com
I think that will include parent node as well. I need to fetch only those nodes which are at the bottom most heirarchy.

For ex:

Parent1
  - Child 1
     -Sub Child 1
     -Sub Child 2
     -Sub Child 3
Parent2
  - Child 2
     -Sub Child 4
     -Sub Child 5
     -Sub Child 6
Parent3
  - Child 3
     -Sub Child 7
     -Sub Child 8
     -Sub Child 9

Now I need to count only "Sub Childs". Condition is that all nodes are closed initially.

Ivan Bozhanov

unread,
Mar 5, 2014, 5:24:13 AM3/5/14
to jst...@googlegroups.com
Ah, sorry - I was too quick to answer.
Well - get that result (from get_json) and instead of using .length loop through it, and only count nodes that have a children array that is zero length:

var res = instance.get_json('#', { flat : true });
var cnt = 0;
for(var i = 0, j = res.length; i < j; i++) {
  if(!res[i].children || !res[i].children.length) { cnt++; }
}

// cnt is what you need.

Gulam sarwar

unread,
Jan 27, 2017, 12:54:42 PM1/27/17
to jsTree
var res = jQuery.jstree.reference('#divJsTree').get_json('#', { flat: true });
                var cnt = 0;
                for (var i = 0, j = res.length; i < j; i++) {
                    if (res[i].parent !== '#') {
                        cnt++;
                    }
                }
Reply all
Reply to author
Forward
0 new messages