cambraca
cambraca

Reputation: 27837

Determining if the element is the last child of its parent

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

Upvotes: 74

Views: 65380

Answers (3)

Jonatan Littke
Jonatan Littke

Reputation: 5663

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

}

Upvotes: 11

Rafael
Rafael

Reputation: 18522

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

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

Upvotes: 149

Nick Craver
Nick Craver

Reputation: 630627

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.

Upvotes: 18

Related Questions