AD JB Toolbox 01 EN

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

.each() runs a callback once for each matched element. It supplies a zero-based index and the DOM element, and return false stops further iterations.

Syntax and behavior

$(".item").each(function (index, element) {
  // this and element refer to the current DOM element.
});

Inside a regular callback, this is the current DOM element, not a jQuery object. Wrap it with $(this) to use jQuery methods. Arrow functions have a different this binding; use their element parameter instead. The method returns the original jQuery object, not an array of callback return values. Use .map().get() when collecting an array of results.

The official jQuery .each() documentation describes additional call signatures and argument types.

Complete runnable example

Save the following code as a UTF-8 example.html file and open it in a browser. It loads the full jQuery 4.0.0 build from an external URL, so an internet connection is required. The $(function () { ... }) callback waits for the document to be ready before running the example.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery each example</title>
  <style>
    body { margin: 24px; font-family: sans-serif; line-height: 1.6; }
    .marked { background: #fff0b3; border: 2px solid #835b00; }
    .active { color: #a00000; font-weight: bold; }
    button, input, select { font: inherit; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
<ul><li class="item">First</li><li class="item">Second</li><li class="item">Third</li></ul>
  <p id="output" aria-live="polite"></p>
  <script>
    $(function () {
      const visited = [];
      $(".item").each(function (index, element) {
        $(element).addClass("marked");
        visited.push(index + ":" + $(this).text());
        if (index === 1) { return false; }
      });
      $("#output").text(visited.join(" / "));
    });
  </script>
</body>
</html>

Expected result

Only First and Second are highlighted. The output is 0:First / 1:Second. The callback completes the work for index 1 and then returns false, so Third is not processed.

Using the element parameter in an arrow function

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

This sets data-index to 0, 1, and 2 on all three items. It avoids relying on this from an outer scope.

Important details and troubleshooting

  • To skip only the current item, return before performing that item’s work. Returning false stops every later iteration as well.
  • Setters such as .addClass() already apply to all matched elements. You do not need .each() merely to add the same class to each one.
  • $.each(array, callback) is a separate API for iterating general arrays and objects. Distinguish it from .each() on an element collection.
  • An async callback does not make .each() wait for asynchronous work. Use an appropriate construct such as for...of with await when completion must be sequential.

Compare the behavior with .addClass() and CSS classes.

More in This Category
jQuery .each(): Iterate over Elements and Stop a Loop

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

Use callback indices and element references, stop a loop correctly, and avoid confusing element iteration with asynchronous sequencing.

jQuery .slideDown(): Expand and Show Hidden Content

jQuery .slideDown(): Expand and Show Hidden Content

Reveal a hidden panel and handle its initial state, animation queue, callbacks, reset behavior, and reduced motion.

jQuery .has(): Select Elements with Matching Descendants

jQuery .has(): Select Elements with Matching Descendants

Filter the original selection by matching descendants, and see why has and find return different elements.

jQuery .add(): Combine Element Selections

jQuery .add(): Combine Element Selections

Combine selections without changing the original collection, and distinguish selecting elements from inserting them into the document.

jQuery .slideUp(): Collapse and Hide Content

jQuery .slideUp(): Collapse and Hide Content

Collapse a panel with duration, easing, and completion handling, including queued effects, reset behavior, and reduced motion.

jQuery .addClass(): Add One or More CSS Classes

jQuery .addClass(): Add One or More CSS Classes

Add one or more classes while preserving existing names, generate classes with a callback, and check why styling may not change.

jQuery :button Selector: Which Elements Does It Match?

jQuery :button Selector: Which Elements Does It Match?

Check how :button treats button elements, ordinary button inputs, and submit or reset inputs, with a working selection example.

jQuery .removeClass(): Remove Specific or All Classes

jQuery .removeClass(): Remove Specific or All Classes

Remove selected class names or clear all classes, while distinguishing class removal from clearing inline styles.

jQuery .unwrap(): Remove a Parent and Keep Its Children

jQuery .unwrap(): Remove a Parent and Keep Its Children

Remove matching immediate parents while preserving their children, and understand layout, event, and restoration implications.

jQuery .slideToggle(): Toggle a Collapsible Panel

jQuery .slideToggle(): Toggle a Collapsible Panel

Build a collapsible panel with a state-aware button, animation queue control, and collection-wide completion handling.