tags:

views:

1019

answers:

4

I have a 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?

+6  A: 

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

$(xml).find("strengths").each(function() {

    if (iWantToBreak)
        return false;
});
Greg
Thank you very much Greg.
Colour Blend
+5  A: 

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).

Guffa
Nice to know what return true does too. Thanks.
Aaron Wagner
+1 for the return true. Thanks.
Colour Blend
+1  A: 
if (condition){
return false
}

see similar question asked 3 days ago.

adardesign
+1  A: 

Does a simple return work?

if (<condition>) { return; }
keithjgrant