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
:
$('ul li').eq(X);
Where X is a 0-based index of which element you want. You could also use the selector form:
$('ul li:eq(X)');
And you could also achieve a similar result by using nth-child
:
$('ul li:nth-child(X)');
The documentation has this to say about the difference between nth-child
and eq
:
While :eq(index) matches only a single element, this matches more than one: One for each parent with index. Multiple for each parent with even, odd, or equation. The specified index is one-indexed, in contrast to :eq() which starts at zero.
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:
var $ul = $('#mylist > li');
var $el = $ul.eq($ul.length-2);
But you should probably do a check to make sure length-2 is not less than 0.
Do you want the 3rd from last?
var $ul = $("ul li");
$ul.find(":eq(" + Math.max(0, $ul.length - 3) + ")");
Quick explanation: The length of $ul (which is a jQuery object) is how many li's are found. So you can use that along with the ":eq(n)" selector to get the li at the desired index.
I used Math.max in case the list was too short (less than 3 li's).
This will also work, but it's obviously not the best way:
var $ul = $("ul li:last").prev().prev();
For third and twentieth, you can do ul li:eq(3)
and ul li:eq(20)
. For second to last, you might be able to do something with nth-child
's equation
argument option, though I'm not sure.
alert($('ul li').eq(3).text());
That will alert the text of the third list item.
The jQuery team added this feature in version 1.9
You can read about it at http://api.jquery.com/nth-last-child-selector/