jQuery: how do I check if an element is the last sibling?

Jquery

Jquery Problem Overview


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().

Jquery Solutions


Solution 1 - Jquery

This is more elegant and worked for me:

if($(this).is(':last-child'))
{
    alert('123');
}

Solution 2 - Jquery

Try

$('tr td:last-child').each(function(){
    var $this = $(this);
    alert('123');
});

Solution 3 - Jquery

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');
        }
})

Solution 4 - Jquery

you can code this way.

var $this = $(this);
if($this.index()==$this.siblings().size()-1)
{
   alert("It's the last.");
}

Solution 5 - Jquery

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
    }
})

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
QuestionHaroldoView Question on Stackoverflow
Solution 1 - JquerybbeckfordView Answer on Stackoverflow
Solution 2 - JqueryrahulView Answer on Stackoverflow
Solution 3 - JqueryntziolisView Answer on Stackoverflow
Solution 4 - JquerylegendJSLCView Answer on Stackoverflow
Solution 5 - JqueryCaner SAYGINView Answer on Stackoverflow