jQuery break out of a foreach loop

Sam Deering

Simple jQuery code snippet to break out of a foreach loop using jQuery’s .each() function when you’ve found the value your looking for you might not need to loop through the rest of the results.

var selected = 0;
// Iterate through item in the list.  If we find the selected item, return false to break out of the loop
$('ul#mylist li').each(function(index){
  if ( $(this).hasClass(‘selected’) )
    selected = index;
    return false; 
console.debug('Selected position is: '+ selected);