I looked quite a bit for a solution for this but I surprisingly couldn't find anything. Maybe I just didn't search for the right words. I found a bunch of questions about getting the index by the element, but I need the opposite.
I'm trying to use javascript and jquery get an element in an ordered list by it's 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 one (Zero
) by its index of 0, or the second one (One
) by its index of 1.
So far I have tried a few things:
A simple function based off of the getting the index of an object in a list using the id.
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's 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? Thanks.