Thursday, May 21, 2009

‘break’ and ‘continue’ for jQuery loop

jQuery functions like $.each( Object obj, Function fn ) or $().each() are not loop rather these are iterative functions. $().each() is used to iterate over a jQuery object and you can use $.each( Object obj, Function fn ) to iterate over anything (for example, an array). As they iterate over something we call them loop.

So jQuery loops are not like javascript loops.

We use ‘break;’ and ‘continue;’ inside a loop. These will not work inside a jQuery loop (like $.each()). So what you will do, if you need the same functionality for a jQuery loop. Fortuitously there is another way. You can use ‘return false;’ inside a jQuery loop to break it. The idea is simple. jQuery loops are functions. So when you ‘return false;’ from a function, it will immediately stop execution of that function and will not continue. Which will work as ‘break;’. Similarly if you write ‘return;’ (without an argument) it will work as ‘continue’;

Here are two examples:-

$("#tblId tr").each(function(i, obj) {

    If($(obj).attr('id')==’idBreakHere’) {

        return false; //this is equivalent of 'break' for jQuery loop



$("#tblId tr").each(function(i, obj) {

    If($(obj).attr('id')!=’idToFind’) {

        return; //this is equivalent of 'continue' for jQuery loop




1 comment:

Sohel said...

Hi Ron,
Thanks for your example.
Really this very simple.

But if anyone don't know then it is hard to find out. There is no help in Jquery API also.