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

5

15

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.

Gothicism answered 22/9, 2011 at 12:4 Comment(5)
What doesn't work? That is correct. In fact that is almost the exact example on jquery's page? api.jquery.com/getVandiver
somehow it doesn't work... do not know why!Gothicism
my example: $('li').get(0).show(); ? returns that it's not a function at all.Gothicism
it works with eq and nth-child though. :) thanks!Gothicism
try to alert($('ul li').get(0)) what it will give youGlisten
L
22

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
Lilias answered 22/9, 2011 at 12:10 Comment(1)
thanks, works perfectly with eq function, or in jQuery selector argument ;) thanks!Gothicism
B
4

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

 $("ul li:eq(1)"); 
Biz answered 22/9, 2011 at 12:9 Comment(0)
P
1

I would try:

$("ul li:nth-child(2)")
Pinion answered 22/9, 2011 at 12:8 Comment(0)
A
1

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

Askari answered 22/9, 2011 at 12:12 Comment(1)
thank you for the tip man, I didn't know it before man. thanks man!Gothicism
D
0

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/

Decade answered 22/9, 2011 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.