A. Appleby
A. Appleby

Reputation: 469

How can I confirm that an element is the first of its class in jQuery?

I need to know whether the element being clicked on is the first of its kind, because if it is, I need to uncheck a checkbox and re-run a function that prevents inputs being matched; however, something that I thought would be seemingly simple is apparently not that simple. I thought it would be as simple as:

$(".remove-box").unbind().click(function (e) {
    e.preventDefault();

    if($(this) == $(".remove-box :first")) {
        //uncheck tickbox and remove matching details class
    }

    removeDelegate($(this));
});

Has anyone got any suggestions for how I can make this work?

Upvotes: 2

Views: 48

Answers (3)

Nick G
Nick G

Reputation: 1973

You can just do $(".remove-box").first();. $(".remove-box") will get you all of the elements with that class, .first() will get you the first of those selected elements.

Edit: By the way, for current major desktop browsers, use your selector followed by .first() rather than :first in your selector. Using the function is much quicker, here is a site that you can run tests on to check performance of certain selectors.

Upvotes: 2

Havana Sette
Havana Sette

Reputation: 21

$(".remove-box").unbind().click(function (e) {
    e.preventDefault();
    var $firstRemBox=$(this).parent().find(".remove-box").first();
    if($(this) == $firstRemBox) {
        //uncheck tickbox and remove matching details class
    }
    removeDelegate($(this));
});

But I think that's better:

$(".remove-box").off().one('click',function(e){
    e.preventDefault();
    var $firstRemBox=$(this).parent().find(".remove-box").first();
    if($(this) == $firstRemBox) {
        //uncheck tickbox and remove matching details class
    }
});

Upvotes: 2

Mitya
Mitya

Reputation: 34556

By "first of its kind" I assume you mean its type, i.e. tag. In which case:

if ($(this).is(':first-of-type)) {

If you mean first of a certain class, it gets more involvd. First of a certain class in the entire document? In the current container? Assuming the latter:

if ($(this).prevAll('.className').length) {

Upvotes: 3

Related Questions