jQuery Tip: How to break out of .each()
I’m working on a dynamic page using jQuery where I have an unordered list of 12 items, one of which will randomly have the class “selected.” My goal was to find out the position in the list of the “selected” item. I hunted around the various properties I could get from a jQuery selector and didn’t find what I was looking for so I ended up with the following solution as illustrated by the following HTML and JavaScript.
1 <ul id=”mylist”> 2 <li>Item #1</li> 3 <li>Item #2</li> 4 <li class=”selected”>Item #3</li> 5 … 6 <li>Item #12</li> 7 </ul>
Using the following JavaScript, I was able to determine the position of the li with the selected class:
1 var selected = 0; 2 // Iterate through item in the list. If we find the selected item, return false to break out of the loop 3 $(‘ul#mylist li’).each(function(index){ 4 if ( $(this).hasClass(‘selected’) ) 5 { 6 selected = index; 7 return false; 8 } 9 }); 10 console.debug(‘Selected position is: ’ + selected);
I had spent so much time looking for a function or selector to help me with this issue, I overlooked the obvious, I could keep a counter of my position in the .each() function and then break out from there. But I was faced with a problem, I didn’t know how to break out of an each. The context of it is fairly odd, from a procedural standpoint. Thankfully, Rey Bango had the solution: returning false.
As illustrated in the above code snippet, returning false from an .each() will act like a traditional loop break. If you have any solutions for solving my original problem, I’d love to hear them.