jQuery each function, continue or break

Error message

Deprecated function: Methods with the same name as their class will not be constructors in a future version of PHP; GeSHi has a deprecated constructor in require_once() (line 915 of /home/digipiph/public_html/sites/all/modules/libraries/libraries.module).

A problem I run into all the time is how to use the equivalent of PHP's "continue" function with jQuery's "each" function. So I guess it is time to document it.

We can break jQuery's $.each() loop at a particular iteration by making the callback function return "false". If we return "true", it is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

For example:

<table>
  <tr>
    <td>1</td>
    <td>1</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
  </tr>
</table>
 
<script>
  $('table td').each(function() {
    if ($(this).html() == "1") {
      return; //this is equivalent of 'continue' for jQuery loop    
    }
    if ($(this).html() == "4") {
      return false; //this is equivalent of 'break' for jQuery loop    
    }
 
    $(this).remove();
  });
</script>

The result of the above code would "continue" past the table cells that have"1" and would terminate once it hits a table cell that has "4". So therefore the table cell that has the html of "3" would be removed.

The resulting table would be:

<table>
  <tr>
    <td>1</td>
    <td>1</td>
    <td>4</td>
    <td>5</td>
  </tr>
</table>

Tags: