I have written following JQuery code to traverse the HTML markup pasted below. Basically I am selecting data-icount attribute of each anchor tag and appending it to anchor text as (28) e.g. the ALL becomes ALL (38) in the example code below. 38 here is the sum of all the data-icounts under that li ... similarly summers become summers (2) because it has two data-icount 0 and 2 so 0+2 =2. Working example here ... http://jsfiddle.net/GQkB8/
I am sure there must be a improved process to do this - any comments/suggestions would be appreciated.
<script>
$(document).ready(function(){
var $lis = $("#tree li");
$lis.each(function(index) {
var $this = $(this);
var $sub_uls = $this.children('ul');
var $child_a = $this.children('a');
var num_sub_uls = $sub_uls.length;
var count_icount = 0;
if(num_sub_uls > 0) {
//var sub_lis = $this.children('a');
var sub_lis = $sub_uls.find('a');
//console.log('Total anchors: '+sub_lis.length);
sub_lis.each(function(index2) {
count_icount += parseInt($(this).attr('data-icount'));
//console.log(count_icount);
});
//console.log("out of loop");
} else {
count_icount = parseInt($child_a.attr('data-icount'));
}
var a_txt = $child_a.text();
$child_a.text(a_txt+' ('+count_icount+') ');
});
});
</script>
//HTML Markup
<ul id="tree" class="tree">
<li class="">
<a data-icount="0" href="/some/thing/1">ALL </a>
<ul >
<li class="">
<a data-icount="7" href="/some/thing/2" >Fruits</a>
<ul >
<li class="">
<a data-icount="5" href="/some/thing/4" >Summers</a>
<ul >
<li class=""><a data-icount="0" href="/some/thing/7">Mango</a></li>
<li class=""><a data-icount="2" href="/some/thing/8" >Water melon</a></li>
</ul>
</li>
<li class="">
<a data-icount="0" href="/some/thing/5" >Winters</a>
<ul >
<li class=""><a data-icount="0" href="/some/thing/9" >Tangerines</a></li>
<li class=""><a data-icount="0" href="/some/thing/10" >Pomegranate</a></li>
</ul>
</li>
<li class=""><a data-icount="1" href="/some/thing/12" >Others</a></li>
</ul>
</li>
<li class="open">
<a data-icount="0" href="/some/thing/3" class="selected">Furniture</a>
<ul >
<li class=""><a data-icount="6" href="/some/thing/6" >Home</a></li>
<li class=""><a data-icount="0" href="/some/thing/11" >Garden</a></li>
</ul>
</li>
<li class=""><a data-icount="10" href="/some/thing/13" >Games</a>
<ul >
<li class=""><a data-icount="5" href="/some/thing/36" >Playstation</a></li>
</ul>
</li>
<li class=""><a data-icount="2" href="/some/thing/37" >Clothes</a></li>
</ul>
</li>
</ul>