jQuery .each(): Iterate over Elements and Stop a Loop

jQuery .each() visits each matched element in turn and runs a callback. Use return; to skip the rest of the current callback, or return false; to stop the loop entirely.

Understand index, element, and this

In the official jQuery .each() documentation, the first parameter index is the zero-based position in the matched collection. The second, element, is the current DOM element. In a regular function, this refers to that same element. Wrap either one in $() to call jQuery methods.

$(".item").each(function (index, element) {
  console.log(index, this === element);
});

.each() still returns the original jQuery object after a stop, so you can chain another method. To collect an array of values, make the values with .map() and then call .get().

Complete runnable browser example

Save the code as a UTF-8 file named example.html. Open it in a browser with internet access to load jQuery 4.1.0. The highlights and output are recalculated each time you change a checkbox.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery .each() loop example</title>
  <style>
    body { max-width: 34rem; margin: 1rem auto; padding: 0 1rem; font: 1rem/1.5 system-ui; }
    label { display: block; margin: .4rem 0; }
    .item { margin: .4rem 0; padding: .25rem .5rem; }
    .marked { background: #fff0b3; outline: 2px solid #835b00; }
  </style>
  <script src="https://code.jquery.com/jquery-4.1.0.min.js"></script>
</head>
<body>
  <label><input id="skip" type="checkbox" checked> Skip the second item</label>
  <label><input id="stop" type="checkbox" checked> Stop after the fourth item</label>
  <ol id="items">
    <li id="a" class="item">First</li>
    <li id="b" class="item" data-step="skip">Second</li>
    <li id="c" class="item">Third</li>
    <li id="d" class="item" data-step="stop">Fourth</li>
    <li id="e" class="item">Fifth</li>
  </ol>
  <p>Processed items <output id="output" aria-live="polite"></output></p>
  <script>
    $(function () {
      const $items = $("#items .item");

      function update() {
        const skip = $("#skip").prop("checked");
        const stop = $("#stop").prop("checked");
        const visited = [];
        $items.removeClass("marked");

        $items.each(function (index, element) {
          if (skip && element.dataset.step === "skip") return;
          $(element).addClass("marked");
          visited.push(index + ": " + $(this).text());
          if (stop && element.dataset.step === "stop") return false;
        });

        $("#output").text(visited.join(" / "));
      }

      $("#skip, #stop").on("change", update);
      update();
    });
  </script>
</body>
</html>

Compare skipping an item and stopping

  1. Both options start enabled. The second item is skipped by an early return;. The fourth is highlighted and added to the output before return false;. The output is 0: First / 2: Third / 3: Fourth.
  2. Turn off Stop after the fourth item. The fifth item is now processed, so 4: Fifth is added to the output.
  3. Turn off Skip the second item as well. All five items are highlighted and the output shows indexes 0, 1, 2, 3, 4.

Skipping the second item leaves the third item’s index at 2. The index is a position in the selection. To leave the stopping item untouched too, put return false; before its changes.

Use element in an arrow function

An arrow function inherits this from the surrounding scope. When using one with .each(), refer to the DOM element through the element parameter.

$(".item").each((index, element) => {
  $(element).attr("data-index", index);
});

Run this snippet in the example page’s developer console. It sets data-index from 0 to 4 on all five items. This is a separate call with no checkbox conditions.

Choose a different iteration method

  • To add one class to every matched element, call jQuery .addClass() directly. $(".item").addClass("marked") already applies to each match.
  • To loop through a plain array or object, use jQuery.each(). Its callback receives an index and value for an array, or a key and value for an object.
  • .each() does not wait for async callbacks. When one task must finish before the next, use for...of over $items.get() with await inside an async function.