Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class to particular li?

I have this HTML:

<ul class="how-long">
    <li value="1">Any</li>
    <li value="1">1 day</li>
    <li value="2">Week end</li>
    <li value="7">1 Week</li>
    <li value="14">2 Week</li>
    <li value="21">3 Week</li>
</ul>

On document ready I want to add new class to the 4th li element.

This is what I tried:

$(".how-long li").slice(3).addClass('change-color');

If I put an alert as:

alert($(".how-long li").slice(3).html());

it gives me 1 week which is right, but when I addclass the class is added to all li after 4th li.

I want to this without adding ID to each li element. I can hard code class in li element directly but I want to do it dynamicaly using jQuery.

like image 818
sandip Avatar asked Nov 29 '22 08:11

sandip


1 Answers

To do it in one selector, use nth-child or eq:

nth-child is considerably faster, see my jsPerf here: http://jsperf.com/nth-child-vs-eq

jsperf

nth-child:

$(".how-long li:nth-child(4)").addClass('change-color');

eq:

$(".how-long li:eq(3)").addClass('change-color');

The fundamental difference is that nth-child will give you the 4th element of every item with that class (regardless of whether it is a child of the current item), whereas eq will give you the children on the current item.

like image 155
mattytommo Avatar answered Dec 10 '22 21:12

mattytommo