views:

18

answers:

1

I'm building a jQuery plugin that works with multiple unordered lists. I want to be able to give each li tag in each list an index-numbered class name, starting over with 1 in each list, like so:

<ul class="ui-tabs-panel">
    <li class="col-1">column 1</li>
    <li class="col-2">column 2</li>
    <li class="col-3">column 3</li>
</ul>
<ul class="ui-tabs-panel">
    <li class="col-1">column 1</li>
    <li class="col-2">column 2</li>
    <li class="col-3">column 3</li>
</ul>

This is the code I'm using to do it:

$('.ui-tabs-panel').find('li').each(function(i) {
    $(this).addClass('col-' + (i+1));
});

But instead, the output is this:

<ul class="ui-tabs-panel">
    <li class="col-1">column 1</li>
    <li class="col-2">column 2</li>
    <li class="col-3">column 3</li>
</ul>
<ul class="ui-tabs-panel">
    <li class="col-4">column 1</li>
    <li class="col-5">column 2</li>
    <li class="col-6">column 3</li>
</ul>

Instead of restarting from 1 for each ul, it continues as though it's not numbering a whole new set of li tags.

What do I need to do to make it start the count over with each new ul?

+2  A: 

You're going through all the LIs in one big batch. You have to go through the LIs of each UL separately:

To restart the counter for each UL, you must use nested .each()es.

$('ul.ui-tabs-panel').each(function() {         // Get al ULs with .ui-tabs-panel
    $(this).find("li").each(function(i) {        // Go through each LI of this UL

        $(this).addClass('col-' + (i+1));  // Add the right class

    });
});         

Try it out with this jsFiddle


Note that instead of using classes, you might be able to use the nth child pseudo selector on the fly.

For example to select the 2nd Li in each UL.ui-tabs-panel you would do:

   // Select the second LI in each ul.ui-tabs-panel
$('ul.ui-tabs-panel li:nth-child(2)')  

Try it out with the jsFiddle (hides the second LI in each UL)

Peter Ajtai
Thanks! I had tried using nested .each() functions since posting this question, but I guess I didn't have the syntax quite right.
Tom
@Tom - You're welcome ;)
Peter Ajtai