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 prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.
It is a jQuery Selector used to select every element that is the last child of its parent. Return Value: It selects and returns the last child element of its parent.
The last() function is an inbuilt function in jQuery which is used to find the last element of the specified elements. Here selector is the selected elements. Parameters: It does not accept any parameter. Return value: It returns the last element out of the selected elements.
This is more elegant and worked for me:
if($(this).is(':last-child')) { alert('123'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With