jQuery's loops differs from normal JavaScript loops in how you can exit from them. In a normal JavaScript loop you can use the break
statement to exit from the loop, while in jQuery this is not possible. Instead, you should use the return
statement plus a given condition to make the loop stop. For example, suppose that you're looping through a set of list items and you want to exit from the loop just after the third item has been selected. Here's how you can do:
$('#test li').each(function(i) { $(this).addClass('test'); return (i < 2); });
In this case the loop ends when its index is less than 2. Since the loop starts from 0, you're actually adding a class only to the first three items. Further, the return
statement can be used to make the action of a loop more explicit:
$('#test2 li').each(function() { if(/^[a-z]$/i.test($(this).text())) { return $(this).addClass('test'); } });
Bear in mind, however, that a jQuery loop returns an object by default. You can see this behavior by storing the loop in a variable:
var loop = $(elements).each(function() { // ... }); alert(loop); // [object Object]