Get Element in HTML Ordered List by Index Using Ja

2019-09-06 17:35发布

问题:

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:

  1. 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.
    
  2. 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.

回答1:

There are many ways to do this. You can use :eq selector. Something like this?

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

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

Demo

So, as this is zero indexed. You could do: $('ol li:eq(0)') for getting the first element. You can also use css, nth-child, nth-of-type selector:

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


回答2:

You can use JQuery:

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

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