Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select last child element in jQuery?

How to select last child element in jQuery?

Just the last child, not its descendants.

like image 397
lovespring Avatar asked Jan 06 '11 07:01

lovespring


People also ask

Is jQuery the last element?

The last() function is an inbuilt function in jQuery which is used to find the last element of the specified elements. Here selector is the selected elements. Parameters: It does not accept any parameter. Return value: It returns the last element out of the selected elements.

How do I get the second last Li in jQuery?

You need to use "nth-last-child(2)" of jquery, this selects the second last element.


2 Answers

You can also do this:

<ul id="example">     <li>First</li>     <li>Second</li>     <li>Third</li>     <li>Fourth</li> </ul>  // possibility 1 $('#example li:last').val(); // possibility 2 $('#example').children().last() // possibility 3 $('#example li:last-child').val(); 

:last

.children().last()

:last-child

like image 125
Yoram de Langen Avatar answered Sep 20 '22 17:09

Yoram de Langen


For perfomance:

$('#example').children().last() 

or if you want a last children with a certain class as commented above.

$('#example').children('.test').last() 

or a specific child element with a specific class

$('#example').children('li.test').last() 
like image 30
Philip Avatar answered Sep 21 '22 17:09

Philip