最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - selecting 2nd and 3rd list items in a list with jquery - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 3

The 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');
发布评论

评论列表(0)

  1. 暂无评论