jqueryloopsbreak

How to break out of jQuery each loop?


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.


Solution

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