开发者

selecting 2nd and 3rd list items in a list with jquery

开发者 https://www.devze.com 2022-12-21 16:19 出处:网络
I have a list. <ul id=\"navigation\"> <li><a href=\"#\"></a></li> <li><a href=\"#\"></a></li>

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>
<开发者_Go百科/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


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");


$("#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 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");


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消