Zander17
Zander17

Reputation: 1954

Check whether element in a list is the first

I have a list and I'm using jQuery to allow for list objects to be removed.

$(document).off('click', '#delete').on('click', '#delete',function(e) {
    $(this).parent().remove();
}); 

I was wondering how do I tell if the element being deleted is the first on the list?

Upvotes: 2

Views: 120

Answers (3)

superpuccio
superpuccio

Reputation: 12972

You can also use the .index() position. This function returns a zero based index so, for the first element, you get 0. Another interesting point is that 0, in javascript, is false and all other numbers are true. The .index() function, then, returns false if the element is the first element.

$(document).off('click', '#delete').on('click', '#delete',function(e) {
    if(!$(this).parent().index()){
        //the element is the first element
    }
});

This is the full DOC for the .index() function.

Upvotes: 2

haim770
haim770

Reputation: 49095

You can use the is method:

if ($(this).parent().is(':first-child'))
{
}

See Documentation

Upvotes: 1

edhedges
edhedges

Reputation: 2718

You could use is and :first

So it would be something like:

if($(this).parent().is(':first')) {
    // this was the first element
}

Upvotes: 1

Related Questions