JQuery: how to check if an element is the last sibling?

How to check if an item is the last sibling?

For the last cell in the row, I want to perform another action.

This does not work:

$('td').each(function(){ var $this = $(this); if ( $this === $this.parent().last('td') ) { alert('123'); } }) 

And also if I remove .parent() .

+47
jquery
Apr 21 '10 at 9:13
source share
4 answers

Try

 $('tr td:last-child').each(function(){ var $this = $(this); alert('123'); }); 
+11
Apr 21 '10 at 9:14
source share
— -

This is more elegant and worked for me:

 if($(this).is(':last-child')) { alert('123'); } 
+274
Jan 16 2018-12-16T00:
source share

Here you go, but that only makes sense if you want to do something different etc., as well as use the last-child method described in one of the other answers in a different way.

 $('td').each(function(){ var $this = $(this); if ($this.index() == $this.siblings().length-1) { alert('123'); } }) 
+7
Apr 21 '10 at 9:21
source share

you can encode this path.

 var $this = $(this); if($this.index()==$this.siblings().size()-1) { alert("It the last."); } 
+2
Mar 13 '14 at 8:48
source share



All Articles