Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 572
Orson Avatar asked Nov 25 '09 19:11

Orson


People also ask

How can I break exit from a each () function in jQuery?

"We can break the $. each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

How do you exit for each loop?

Officially, there is no proper way to break out of a forEach loop in javascript. Using the familiar break syntax will throw an error. If breaking the loop is something you really need, it would be best to consider using a traditional loop.

How do you stop a function from calling in jQuery?

The stop() method is an inbuilt method in jQuery which is used to stop the currently running animations for the selected element. Syntax: $(selector). stop(stopAll, goToEnd);

What is .each in jQuery?

The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.


2 Answers

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

$(xml).find("strengths").each(function() {      if (iWantToBreak)         return false; }); 
like image 82
Greg Avatar answered Sep 20 '22 16:09

Greg


You can use return false;

+----------------------------------------+ | JavaScript              | PHP          | +-------------------------+--------------+ |                         |              | | return false;           | break;       | |                         |              | | return true; or return; | continue;    | +-------------------------+--------------+ 
like image 37
Subodh Ghulaxe Avatar answered Sep 18 '22 16:09

Subodh Ghulaxe