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?
You’re going through all the
LIs in one big batch. You have to go through theLIs of eachULseparately:To restart the counter for each
UL, you must use nested.each()es.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
Liin eachUL.ui-tabs-panelyou would do:Try it out with the jsFiddle (hides the second LI in each UL)