$().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>
?
$('ul > li').each(function(i) {
$(this).addClass(i + 1);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With