tags:

views:

74

answers:

2

Hi there,

I have multiple lists with the same class.

I'd like to loop each list and its LI's and prepend the current number before each. The current code I have is:

$jQuery(".numberList li").each(function(i) {

    var index = i + 1;

    $jQuery(this).prepend("<span>" + index + "</span>");

});

The problem is, is that the index doesn't restart back at 0 for each list it goes through, it just keeps going up. For example, the output I get now is:

First list
1. item
2. item
3. item

Second list
4. item
5. item
6. item

Second list should start at 1 again by having the index back at 0.

Could someone point out where I'm going wrong? I'm not a jQuery expert or anything...clearly :)

Many thanks, Michael.

+1  A: 

I'd think about nesting loops.

Something like:

$('.numberList').each(function(){
   $this.children('li').each(function(i){
      var index = i + 1;
      $jQuery(this).prepend("<span>" + index + "</span>");
   });
});
timdev
+2  A: 

Why not use just stylesheets?

.numberList {
    list-style-type: decimal;
}

You can apply this style through jQuery if for some reason it has to be done dynamically:

$(".numberList").css("list-style-type", "decimal");​

An example here.

Anurag
This is much better IMHO.
Raja