Reputation: 391
I tried to count the length number and it work, but that method is too much of code.. I tried is() :
$(document).on('click', 'li', function () {
$(this).remove();
if ($(this).is(':last')) {
alert('last');
}
});
http://jsfiddle.net/TgfeT/ It did not work..
Upvotes: 1
Views: 41
Reputation: 99225
You should use :last-child, also the remove comes after the check not before.
$(document).on('click', 'li', function () {
if ($(this).is(':last-child')) {
alert('last');
}
$(this).remove();
});
Upvotes: 0
Reputation: 163
Use this code
$(document).on('click', 'li', function () {
if ($(this).is(':last-child')) {
alert('last');
}
$(this).remove();
});
Upvotes: 0
Reputation: 239250
You're removing it, then asking it if it's the last after it no longer exists in the DOM. That can't work. The last what? It's just a decoupled DOM element at that point.
You need to reverse the order, and ask if it's the :last
before you take it out of its context in the DOM:
if ($(this).is(':last')) {
alert('last');
}
$(this).remove();
Upvotes: 2