Home »
jQuery »
jQuery Examples
How to break out of jQuery each loop?
Learn, what is each() loop in jQuery and how can we break it while execution?
Submitted by Pratishtha Saxena, on August 30, 2022
What is .each() Loop?
This loop is similar to that of while(), do while(), for() loop in JavaScript. But it does not work the same as them. The each() loop searches all the same tags on the HTML page and then runs for each of them. For example – if each() loop is applied for the <p> tag, then all the paragraph tags on the page will be traversed with this loop.
Syntax:
$('selector').each(function(){})
To break out of this loop using jQuery, we'll use return false. It will work as a 'break' statement here. If nothing is specified then it will continue unless all the elements are not traversed. The return true is equivalent to 'continue' and will skip to the next iteration. This is the only way one can break each loop using jQuery.
In the following given example, each() loop is implemented such that each <li> gets traversed and for each of them the function is executed. But when a condition is applied along with return false, then if the condition is true then the loop gets beaked.
Read: Adding jQuery to Your Web Pages
Example to break out of jQuery each loop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>How To Break Out Of jQuery Each Loop</h2>
<ul>
<li>Apple</li>
<li>Mango</li>
<li>Banana</li>
<li>Grapes</li>
<li>Orange</li>
</ul>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('li').each(function(){
var fruit = $(this).text()
console.log(fruit);
if (fruit == 'Banana'){
return false;
}
})
});
</script>
</html>
Output: