Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add classes to li tags in a ul list as an index

$().addClass to <li> tags in a <ul>

example:

<ul>
    <li class="1"></li>
    <li class="2"></li>
    <li class="3"></li>
    <li class="4"></li>
    <li class="5"></li>
</ul>

?

like image 817
Jeff Voss Avatar asked Feb 23 '23 23:02

Jeff Voss


2 Answers

$('ul > li').each(function(i) {
    $(this).addClass(i + 1);
});
like image 193
ThiefMaster Avatar answered Feb 26 '23 21:02

ThiefMaster


The nicest way is with the callback argument to addClass:

$('li').addClass(function(i) {
    return i + 1;
});

The function provided is run once for each element in the selection. The first argument is the 0-based index of the element in the selection (the second is the old class value, but that's unimportant here). The return value is added to the element's current classes.

like image 20
lonesomeday Avatar answered Feb 26 '23 22:02

lonesomeday