73

Using jQuery, is there a quick way of knowing if an element is its parent's last child?

Example:

<ul>
  <li id="a"></li>
  <li id="b"></li>
  <li id="c"></li>
</ul>

$('#b').isLastChild(); //should return FALSE
$('#c').isLastChild(); //should return TRUE
cambraca
  • 27,014
  • 16
  • 68
  • 99
  • 1
    possible duplicate of [jQuery: how do I check if an element is the last sibling?](http://stackoverflow.com/questions/2681581/jquery-how-do-i-check-if-an-element-is-the-last-sibling) – user56reinstatemonica8 Nov 27 '14 at 16:15

3 Answers3

147

Use :last-child selector together with .is()

$('#c').is(':last-child')
Rafael
  • 18,349
  • 5
  • 58
  • 67
18

You can use .is() with :last-child like this:

$('#b').is(":last-child"); //false
$('#c').is(":last-child"); //true

You can test it here. Another alternative is to check .next().length, if it's 0 it's the last element.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
10
if($('#b').is(":last-child")){

}
rrk
  • 15,677
  • 4
  • 29
  • 45
Jonatan Littke
  • 5,583
  • 3
  • 38
  • 40