jQuery each function, continue or break

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:

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
If you have questions about anything on this site, you can find me on Google+: