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?
I put the return false;
in the wrong place. When I put it inside the loop everything worked.
You can stop the loop from within the callback function by returning false . $( this ). addClass( "foo" ); });
We can break the $. each() loop [..] by making the callback function return false. BTW, continue works like this: Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
each(function() { // Code // To escape from this block based on a condition: if (something) return false; }); From the documentation of the each method: Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop).
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
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; } });
According to the documentation return false;
should do the job.
We can break the $.each() loop [..] by making the callback function return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) { var booleanKeepGoing; this; // == valueOfElement (casted to Object) return booleanKeepGoing; // optional, unless false // and want to stop looping }
BTW, continue
works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With