I have a list.
<ul id="navigation">
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
</ul>
And using jquery id like to apply a clas to the 2nd and 3rd list items.
Is there simple code for me to do this?
Thanks
I have a list.
<ul id="navigation">
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
</ul>
And using jquery id like to apply a clas to the 2nd and 3rd list items.
Is there simple code for me to do this?
Thanks
Share Improve this question asked Mar 3, 2010 at 14:58 MarkMark 4883 gold badges13 silver badges30 bronze badges 1- Duplicate of a more general question: stackoverflow./questions/1791796/… – Felix Kling Commented Mar 3, 2010 at 15:03
5 Answers
Reset to default 3The simplest approach is to use the ma separator to group the 2nd and 3rd list items:
$("#navigation li:nth-child(2), #navigation li:nth-child(3)").addClass("name");
$("#navigation li:eq(1), #navigation li:eq(2)").addClass("someClass");
Have a look at the :eq
selector.
While Cletus is right, and the simplest thing you can do is use the standard jQuery ma-separated list, if it turns out you need to choose a whole lot of them, you should start looking at the .nextUntil() and .prevUntil() methods. You'd use them like so:
$("#navigation li:nth-child(2)").nextUntil(":nth-child(4)").addClass("name");
Try it
$("#navigation li:gt(0):lt(2)").addClass("t");
You are looking for the nth child selector.
$("ul li:nth-child(2)").addClass('MyClass');