jquery find by index in a list

12,947

Solution 1

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.

Solution 2

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
Share:
12,947
Val
Author by

Val

Founder and director of Mount Media Ltd a web design agency in London. https://www.mountmedia.co.uk

Updated on June 22, 2022

Comments

  • Val
    Val about 2 years
    <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?