Get an item in an HTML ordered list by index using Javascript

I was looking a bit for a solution for this, but I did not find anything surprising. Perhaps I just did not look for the right words. I found a bunch of questions about getting an index from an element, but I need the opposite.

I am trying to use javascript and jquery to get an item in an ordered list by its index in the list. For example, if I have this list:

<ol>
  <li>Zero</li>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ol>

I would like to be able to get the first ( Zero) at its index 0 or the second ( One) with its index 1.

So far I have tried several things:

  • A simple function based on getting the index of an object in a list using an identifier.

    elem = list.index(0); //To get the first element, but this is not a thing.
    
  • A loop like this:

    //elem is the element I am currently at.
    //Starting at the last element and going to the first.
    var elem = list.getLastChild(); //But list.getLastChild() is apparently
    //not a thing although it is here ([w3c link][1]).
    
    //Start at 0 and go to the index
    //(may/may not need the = before num, but I think I do)
    for(var i=0; i<=num; i++){
        //Set elem to it previous sibling
    elem = elem.getPreviousSibling(); //getPreviousSibling is probably not a thing as
        //well but I couldn't get that far before it broke anyway.
    }
    
    //Return the element at the index
    return elem;
    

So is there a way to do this? Thank.

0
2

. : eq. - ?

var $lis = $('ol li');

for(var i=0; i < $lis.length; i++)
{
    alert($('ol li:eq(' + i + ')').text());
}

, . : $('ol li:eq(0)') . css, nth-child, nth-of-type :

  alert($('ol li:nth-child(1)').text()); // This starts with 1 index, non-zero indexed.
+3

JQuery:

$("ol li:nth-child(1)")
$("ol li:nth-child(n)")

http://api.jquery.com/nth-child-selector/

+2

All Articles