How to get a specific jQuery item from a list of i

2019-02-16 07:08发布

I have this:

<ul>
    <li>first</li>
    <li>second</li>
    <li>third</li>
    <li>fourth</li>
</ul>

Then I select it all with jQuery: $('ul').find('li'); or $('ul li');

How can I, from those two jQuery selectors get the, for instance only second li, or third, and to leave first and fourt alone?

I thought it might work with:

$('myselector').get(indexNumber); // however, it won't work.

Any ideas for this issue? Thanks.

5条回答
对你真心纯属浪费
2楼-- · 2019-02-16 07:31

I would try:

$("ul li:nth-child(2)")
查看更多
太酷不给撩
3楼-- · 2019-02-16 07:37

$('li').get(0) will return plain DOM element. you cannot call jQuery methods on same.

查看更多
仙女界的扛把子
4楼-- · 2019-02-16 07:42

you can use nth-child

$("ul li:nth-child(2)") //this will select second child because it is 1 based index

here is a fiddle http://jsfiddle.net/xyyWh/

查看更多
Animai°情兽
5楼-- · 2019-02-16 07:45

The get method returns the DOM element, so then you would have to wrap it inside a new jQuery object.

You can use the eq method:

var j = $('ul li').eq(1); // gets the second list item
查看更多
Anthone
6楼-- · 2019-02-16 07:53

Use :eq() Selector. For for example, for second element use:

 $("ul li:eq(1)"); 
查看更多
登录 后发表回答