Ricki Vandenbroek
Ricki Vandenbroek

Reputation: 391

detect whether it's the the last element using is()

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

Answers (3)

OneOfOne
OneOfOne

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

Fiddle

Upvotes: 0

Alexey Dmitriev
Alexey Dmitriev

Reputation: 163

Use this code

$(document).on('click', 'li', function () {

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

});

Upvotes: 0

user229044
user229044

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

Related Questions