drake035
drake035

Reputation: 2887

Running code for the first element in jQuery each() loop that satisfies a condition

I know how to run code for first element found in each() loop:

$('.selector').each(function(i, el){
    if ( i === 0) {
        // do something
    }
});

But how to run code for first element satisfying a certain condition in the each() loop?

Something like this:

$('.selector').each(function(i, el){
    if ( first element meeting the condition ) {
        // do A
    }
    elseif ( next elements meeting the condition ) {
        // do B
    }
    else {
        // do C
    }
});

Upvotes: 1

Views: 1509

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240938

You could set a variable outside of the loop and use that to determine whether the condition has been satisfied. Once the condition is satisfied, change the variable to prevent it from being executed again.

Example Here

(function () {
    var conditionSatisfied = false;
    $('.selector').each(function (i, el) {
        if ($(this).hasClass('foo') && !conditionSatisfied) {
            conditionSatisfied = true;
            // ..
        } else {
            // ..
        }
    });
})();

Depending on what you're trying to achieve, you may not actually need a loop. You could just select the element directly. For instance, you could select the .selector element with class .foo, and use either :first/.first() in order to select the first matching element.

$('.selector.foo').first();
$('.selector.foo:first');

Upvotes: 1

If you are trying to do something to the first element that has some text for example just do if (el.text() == 'something') and then call return inside the condition to stop

Upvotes: 0

Related Questions