dubbs dubbs - 10 months ago 42
jQuery Question

Assign class to LI based on its index value

I have an unordered list of LIs and a jQuery variable - I would like to add a class to all the LIs of the jQuery variable and lower.



And jQuery variable = 2, and the class I want to add is called "complete"

So, I want my list to them become:

<li class="complete">One</li>
<li class="complete">Two</li>

How can I achieve this?


You can try : slice()

var number = 2;
$("li").slice(0,number).attr('class', 'complete');

Check the demo : https://jsfiddle.net/d36a5x2h/