How to break/exit from a each() function in JQuery?

JavascriptJquery

Javascript Problem Overview


I have some code:

$(xml).find("strengths").each(function() {
   //Code
   //How can i escape from this block based on a condition.
});

How can i escape from the "each" code block based on a condition?

Update:
What if we have something like this:

$(xml).find("strengths").each(function() {
   $(this).each(function() {
       //I want to break out from both each loops at the same time.
   });
});

Is it possible to break out from both "each" functions from the inner "each" function?

# 19.03.2013

If you want to continue instead of break out

return true;

Javascript Solutions


Solution 1 - Javascript

According to the documentation you can simply return false; to break:

$(xml).find("strengths").each(function() {
   
    if (iWantToBreak)
        return false;
});

Solution 2 - Javascript

You can use return false;

+----------------------------------------+
| JavaScript              | PHP          |
+-------------------------+--------------+
|                         |              |
| return false;           | break;       |
|                         |              |
| return true; or return; | continue;    |
+-------------------------+--------------+

Solution 3 - Javascript

Return false from the anonymous function:

$(xml).find("strengths").each(function() {
  // Code
  // To escape from this block based on a condition:
  if (something) return false;
});

From the documentation of the each method:

> Returning 'false' from within the each > function completely stops the loop > through all of the elements (this is > like using a 'break' with a normal > loop). Returning 'true' from within > the loop skips to the next iteration > (this is like using a 'continue' with > a normal loop).

Solution 4 - Javascript

if (condition){ // where condition evaluates to true 
    return false
}

see https://stackoverflow.com/questions/1784780/how-to-break-out-of-jquerys-each-loop"> similar question asked 3 days ago.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOrsonView Question on Stackoverflow
Solution 1 - JavascriptGregView Answer on Stackoverflow
Solution 2 - JavascriptSubodh GhulaxeView Answer on Stackoverflow
Solution 3 - JavascriptGuffaView Answer on Stackoverflow
Solution 4 - JavascriptadardesignView Answer on Stackoverflow