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.
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.
Share Improve this question edited Mar 5, 2013 at 12:18 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Mar 5, 2013 at 12:16 sandipsandip 3,2895 gold badges34 silver badges54 bronze badges7 Answers
Reset to default 13To 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.
$(".how-long li").eq(3).addClass('change-color');
slice doesn't return a jQuery object, therefore you can't use the method addClass. The right way to do what you intend is:
by index:
$(".how-long li").eq(3).addClass('change-color');
by referencing value:
$(".how-long li[value=7]").addClass('change-color');
If you want to use slice method you need to specify end attribute which you are missing
$(".how-long li").slice(3,4).addClass('change-color');
It selects the 4th because Array index's start from 0.
You could always use $('.how-long li:nth-child(4)');
More information here: http://api.jquery.com/nth-child-selector/
You can use the nth-child selector:
$(".how-long li:nth-child(4)").addClass('change-color');
alert($(".how-long li:nth-child(4)").html());
Do it this way
$(".how-long li:nth-child(4)").attr({'class':'test'});
This will add class test
to the 4th li
Hope this heps