jQuery: How to Break Out of an Each Loop Programming 16 MAR 2015

The ever so useful jQuery javascript library has a homegrown loop function entitled .each(), which allows you to iterate over a jQuery object, and at the same time execute a function for each matched element.

Very useful indeed.

However, sometimes you might need to break out of a loop early (for example, maybe your loop has the potential of carrying on forever – which obviously is not so great for your patiently waiting audience) – and this is how you do it:

To break a $.each() loop, you have to return false in the loop callback function. (Returning true is equivalent to continue in a normal loop, in other words it skips to the next iteration – exactly the opposite of what you are trying to achieve!)

An example:

$(document).ready(function(){
$('.lotsOfTheseClassesExist').each(function(i, item){
alert($(item).prop('id'));
return false; //exits the loop
});
});

So your break statement for a jQuery each() loop is literally return false.

girl in pink high heels and a black leotard with lots and lots of shiny hula hoops

jquery logo

Related Link: http://api.jquery.com/each/

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.