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.
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
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.
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