JavaScript
Article
By Sam Deering

jQuery break out of a foreach loop

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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.

--ADVERTISEMENT--

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);
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?