Jquery: Continue and Break each loop

While working on jquery .each() for iterating child elements many time we need to break or continue each loop. For this in jquery we can use return false for breaking the loop and return true to perform continue operation. Here is sample example for jquery break and continue.
Sample html

<div>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
<ul>
<li>item 11</li>
<li>item 21</li>
<li>item 31</li>
<li>item 41</li>
</ul>
<ul>
<li>item 12</li>
<li>item 22</li>
<li>item 32</li>
<li>item 42</li>
</ul>
</div>

Example of jquery to break each() loop

$('div ul li').each(function(){
if($(this).text() == 'item 11')
return false;
});

Example of jquery for continue each() loop

$('div ul li').each(function(){
if($(this).text() == 'item 11')
return true;
});

Jquery function for nested each break

$('div').children('ul').each(function(){
var flag =true; 
$(this).children('li').each(function(){
if($(this).text() =='item3'){ 
flag=false; return false; 
} 
}); 
if(!flag) return false; 
}); 

With same logic you can perform continue.

Leave a Reply

Your email address will not be published. Required fields are marked *