How can I find the last "li" in "ul" using jQuery?

I want to check li , which is the last li in ul . How can I check that using jQuery?

 <ul id="ulscroller"> <li value="1" class="selected">1</li> <li value="2">2</li> <li value="3">3</li> <li value="4">4</li> <li value="5">5</li> <li value="6">6</li> <li value="7">7</li> <li value="8">8</li> <li value="9">9</li> <li value="10">10</li> <li value="11">11</li> <li value="12">12</li> <li value="13">13</li> <li value="14">14</li> <li value="15">15</li> <li value="16">16</li> <li value="17">17</li> <li value="18">18</li> <li value="19">19</li> <li value="20">20</li> </ul> 
+7
source share
5 answers

Just use the : last-child selector:

 $('#ulscroller li:last-child') 

DEMO: http://jsfiddle.net/f5v6R/

For example, if you want to know if it has a selected class, which you can do

 if ($('#ulscroller li:last-child').hasClass('selected')) { // do something } 
+20
source

You can use .last() matcher

 $('#ulscroller li').last() 
+3
source
 $('ul#ulscroller').children('li').last(); 

http://api.jquery.com/last/

You can also do it like this:

 $('ul#ulscroller').children('li:last-child'); 

http://api.jquery.com/last-selector/

Here is an example to illustrate this: http://jsfiddle.net/TheNix/W92vF/

+1
source

try it

 $(function(){ alert($('#ulscroller li:last-child').val()); }) 
+1
source

Just use the following

 if($('#ulscroller li:last-child')[0] == liTocheck) { alert("This is the last li"); } 

or

 if($('#ulscroller li').last()[0] == liTocheck) { alert("This is the last li"); } 

Here liTocheck is the li to compare

0
source

All Articles