JavaScript
Article

jQuery break out of a foreach loop

By 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);

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.