I’m trying to set up my jQuery selector but I’m not exactly sure how I need to write it.
I’ve got a unordered list that looks something like this:
<ul>
<li>something</li>
<li>something</li>
<li>something</li>
<li>something</li>
<li class="last">something</li>
</ul>
Now I know if I want to select the last child I can do that by using either “ul li.last” or “ul.li:last” but say if I wanted the second from last, or third, or 20th? Now would I do that?
You use
eq:Where X is a 0-based index of which element you want. You could also use the selector form:
And you could also achieve a similar result by using
nth-child:The documentation has this to say about the difference between
nth-childandeq:So by doing
$('ul li').eq(19);you would get the single 20th matched element of the query (so if there is more than one list in the document this won’t get you “all 19th children”, while$('ul li:nth-child(20)');would get you the individual 20th matched list element of each<ul>in the document.EDIT:
To do something like “second to last”, the sane way to do it would be like:
But you should probably do a check to make sure length-2 is not less than 0.