Determining if the element is the last child of its parent

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

$('#c').is(':last-child')

Solution 2 - Jquery

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.

Solution 3 - Jquery

if($('#b').is(":last-child")){

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncambracaView Question on Stackoverflow
Solution 1 - JqueryRafaelView Answer on Stackoverflow
Solution 2 - JqueryNick CraverView Answer on Stackoverflow
Solution 3 - JqueryJonatan LittkeView Answer on Stackoverflow