61

How do I check if an element is the last sibling?

For the last cell in a row I want to perform a different action.

This doesn't work:

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

And neither does it if I remove .parent().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Haroldo
  • 36,607
  • 46
  • 127
  • 169
  • 5
    The reason this doesn't work is because you're comparing two jQuery objects with each other. Objects are only ever equal if they are exactly the same object. `$(this) == $(this)` is false.. Crazy stuff. You example would work if you did `if ( $this.get(0) === $this.parent().last('td').get(0) )`, as it compares the actual DOM elements. (http://api.jquery.com/get) – Matt Apr 21 '10 at 09:27

5 Answers5

325

This is more elegant and worked for me:

if($(this).is(':last-child'))
{
    alert('123');
}
bbeckford
  • 4,467
  • 6
  • 34
  • 48
  • this is way better than selecting the object directly by css. you can use this on variables too. – Galzor Aug 08 '18 at 06:54
  • I want to know why not `$(this).is(':last')` work like above one. – Lying_cat Sep 19 '18 at 08:24
  • 2
    @SkuraZZ There is a subtle difference betweem the selectors; :last-child selects all elements that are the last child of their parent, :last selects the last matched element (see https://api.jquery.com/category/selectors/) – bbeckford Sep 20 '18 at 09:25
13

Try

$('tr td:last-child').each(function(){
    var $this = $(this);
    alert('123');
});
rahul
  • 184,426
  • 49
  • 232
  • 263
8

Here you go, but that only make sense if you want to do something to the other tds as well other wise use the last-child method described in one of the other answers.

$('td').each(function(){
    var $this = $(this);
    if ($this.index() == $this.siblings().length-1)
        {
            alert('123');
        }
})
ntziolis
  • 10,091
  • 1
  • 34
  • 50
5

you can code this way.

var $this = $(this);
if($this.index()==$this.siblings().size()-1)
{
   alert("It's the last.");
}
legendJSLC
  • 437
  • 5
  • 7
0

If you want to select multiple elements which are different tags with a common point, (for ex: all data-foo attribute defined tags like divs, inputs, text areas, etc.) you can follow this code:

var elements = $("*[data-foo]");

elements.each(function (){
    ..
    ..your code
    ..

    if (elements.index(this) == elements.length - 1) {
            ..you are at the end, do something else
    }
})
Caner SAYGIN
  • 527
  • 3
  • 11