views:

100

answers:

5

Hi,

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

A: 

You are looking for the nth child selector.

$("ul li:nth-child(2)").addClass('MyClass');
Vincent Ramdhanie
+1  A: 

The simplest approach is to use the comma separator to group the 2nd and 3rd list items:

$("#navigation li:nth-child(2), #navigation li:nth-child(3)").addClass("name");
cletus
A: 
$("#navigation li:eq(1), #navigation li:eq(2)").addClass("someClass");

Have a look at the :eq selector.

karim79
+1  A: 

While Cletus is right, and the simplest thing you can do is use the standard jQuery comma-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");
D_N
I don't see why `nth-child` is necessary in any of the answers here, can someone clarify? OP has a single UL. What am I missing?
karim79
@karim79 nth-child has to do with the LI, not the UL. Though I think you get that, I don't think I get the objection. Both eq() and nth-child() are running index on the same list, just that eq counts from 0 and nth counts from 1. eq() is just as good, I just prefer nth-child() because I think in CSS selectors, and it has a lower learning curve (I think) since there's no counting up from 0, and the name makes more apparent sense.
D_N
Also, when I wrote my response, I didn't see yours, or I'd have mentioned it. They both, in this instance, give the same result.
D_N
@DN - agreed, they are just two different ways to do the same thing, `eq` just seemed to make more sense to me, for this purpose at least. +1 for `nextUntil` by the way.
karim79
Thank you all for your responses. I have not come across nextUntil before, but sounds like it could in use more often. Im guessing this would enable to to grab say <li> 3-6 then add class or similar?
Mark
Yes, the only thing to keep in mind is that nextUntil doesn't include the element matched--so, nextUntil(something) means it will select everything up UNTIL that something. (So my original example was one off--fixed now.)
D_N
A: 

Try it

$("#navigation li:gt(0):lt(2)").addClass("t");
Boris Shemigon