Christian Heilmann

Determining the depth of a nested HTML list

Monday, March 26th, 2007 at 3:29 pm

I had this problem the other day that I needed to know how many nesting levels a menu has. After some failed attempts of walking the DOM and lots of comparisons I realised that it is actually a lot easier than I thought:

function treedepth(o){
var nested = o.getElementsByTagName(‘ul’);
var allcount = 0;
for(var i=0,j=nested.length;i<;i++){
var count = 1;
var kid = nested[i].getElementsByTagName(‘ul’)[0];
while(kid!==undefined){
count++;
kid = kid.getElementsByTagName(‘ul’)[0];
}

if(count>allcount){allcount=count;}
}

return allcount;
}

You can check a testcase for treedepth here.

Any better way to do this?

Share on Mastodon (needs instance)

Share on Twitter

My other work: