How to get a specific jQuery item from a list of items?

拥有回忆 提交于 2019-11-30 22:21:28

问题


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.


回答1:


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



回答2:


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

 $("ul li:eq(1)"); 



回答3:


I would try:

$("ul li:nth-child(2)")



回答4:


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




回答5:


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/



来源:https://stackoverflow.com/questions/7514448/how-to-get-a-specific-jquery-item-from-a-list-of-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!