How to break out of jQuery each Loop

Luke101 picture Luke101 · Nov 23, 2009 · Viewed 529.1k times · Source

How do I break out of a jQuery each loop?

I have tried:

 return false;

In the loop but this did not work. Any ideas?

Update 9/5/2020

I put the return false; in the wrong place. When I put it inside the loop everything worked.

Answer

Christian C. Salvadó picture Christian C. Salvadó · Nov 23, 2009

To break a $.each or $(selector).each loop, you have to return false in the loop callback.

Returning true skips to the next iteration, equivalent to a continue in a normal loop.

$.each(array, function(key, value) { 
    if(value === "foo") {
        return false; // breaks
    }
});

// or

$(selector).each(function() {
  if (condition) {
    return false;
  }
});