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 .find(): Select Matching Descendants

jQuery .find(): Select Matching Descendants

Search through descendant levels while excluding the container, and compare find with children, filter, and has.

jQuery .css(): Read, Set, and Clear Styles

jQuery .css(): Read, Set, and Clear Styles

Read computed styles, set and clear inline properties, and handle CSS units and numeric values in jQuery 4.0.

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 .removeAttr(): Delete HTML Attributes

jQuery .removeAttr(): Delete HTML Attributes

Compare deleting an attribute with setting an empty value, and handle input values, current properties, and ARIA attributes correctly.

jQuery .toggleClass(): Toggle a Class or Set Its State

jQuery .toggleClass(): Toggle a Class or Set Its State

Distinguish reversing a class from setting a known Boolean state, with a toggle-button example and current syntax.

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 .empty(): Clear Content and Keep the Container

jQuery .empty(): Clear Content and Keep the Container

Clear a container’s elements and text without deleting it, refill it, and understand how field values and event handlers differ.

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.

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 .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.