-1

can i have the implmentation for jQuery.each wherein if i find any match within the array which is been processed in jQuery.each, then i can break / return without further process the remaining elements.

<ul>
<li>foo</li>
<li>bar</li>

You can select the list items and iterate across them:

$( "li" ).each(function( index ) {
  //if($(this).text() == 'foo') , i.e if foo is found , 
//then return instead of processing bar.
});
ismail baig
  • 861
  • 2
  • 11
  • 39
  • 2
    You should consider reading [the documentation](http://api.jquery.com/jQuery.each/) when you have questions like this: "_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._" – jahroy Mar 30 '13 at 07:42

3 Answers3

3

return false does that :

var elem;

$( "li" ).each(function() {
    if($(this).text() == 'foo') {
        elem = this;
        return false;
    }
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Nice, Short explanation. And returning false means `break` and returning true means `continue` –  Mar 30 '13 at 07:42
2

From the documentation.

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

http://api.jquery.com/jQuery.each/

SteveP
  • 18,840
  • 9
  • 47
  • 60
1

From the jQuery documentation:

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.

Example:

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>

<script>

    var arr = [ "one", "two", "three", "four", "five" ];
    jQuery.each(arr, function() {
        $("#" + this).text("Mine is " + this + ".");
        return (this != "three"); // will stop running after "three"
    });

</script>`
jahroy
  • 22,322
  • 9
  • 59
  • 108