views:

24

answers:

2
<ul>
  <li>No</li>
  <li>Yes</li>
  <li>No</li>
</ul>

//demostration purpose 
$('ul').get(2).text();


//output = Yes

What's the best way to access a specific item in a list? and use it as a selector?

+3  A: 

You can use .eq() or :eq() to get the jQuery object in a list:

$('ul li').eq(1).text();
//or:
$('ul :eq(1)').text();

You can try a demo here. When you get .get() you're getting a DOM element, which doesn't have any jQuery functions on it. Remember that both of these are 0-based so you'll need 1 to get the "Yes" in your example.

There are also other basic filters you may be interested in, for example :lt() (less-than-index), :gt() (greater-than-index), :first, :last and several others.

Nick Craver
@Andy - Was noticing in my example page, just woke up :)
Nick Craver
@Nick: `nth-child(n)` doesn't accept a zero-based number so I used to always confuse the two and have to double-check. Really, it's the spec's fault for being inconsistent. Anyway, I only edited it to justify my +1 :p
Andy E
@Andy - Agreed, I consider `:nth-child()` a red-headed step-child at this point, I actually so rarely use the thing in practical everyday usage anyway. Maybe once we drop support for IE7 *and* IE8 (already dropped 6, wooohoo!) I can start using it for something in CSS, but in jQuery I've found it not to be very useful at all.
Nick Craver
@Nick: Just thinking about the day people can drop support for IE8 brings a joyful tear to my eye ;)
Andy E
A: 

Use :eq filter selector:

$('ul li:eq(0)').text(); // gets first li
$('ul li:eq(1)').text(); // gets second li
$('ul li:eq(2)').text(); // gets third li
// and so on
Sarfraz