How to select the last child in jQuery?

How to select the last child in jQuery?

Just the last child, not his descendants.

+59
jquery
Jan 6 2018-11-11T00:
source share
4 answers

You can also do this:

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

: last

. children (). last ()

: last-child

+88
Jan 06 2018-11-11T00:
source share
 $('#example').children().last() 

or if you want the last children with a particular class to comment above.

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

or specific child with a specific class

 $('#example').children('li.test').last() 
+28
Mar 05 '14 at 14:28
source share

Using : last-child selector ?

Do you have a specific scenario in which you need help?

+8
Jan 06 2018-11-11T00:
source share

If you want to select the last child and need to be specific by type of element, you can use the last-of-type selector

Here is an example:

 $("div p:last-of-type").css("border", "3px solid red"); $("div span:last-of-type").css("border", "3px solid red"); <div id="example"> <p>This is paragraph 1</p> <p>This is paragraph 2</p> <span>This is paragraph 3</span> <span>This is paragraph 4</span> <p>This is paragraph 5</p> </div> 

In the above example, both in paragraph 4 and in paragraph 5 there will be a red border, since paragraph 5 is the last element of type "p" in the div, and paragraph 4 is the last "span" in the div.

0
Mar 01 '17 at 16:47
source share



All Articles