Iterate Over a jQuery Object Using .each()

The jQuery .each() method is a built-in iterator used to loop through matched DOM elements in a jQuery collection seamlessly. This article explains how to use the .each() method, covering its core syntax, how to access element indices and DOM nodes, the difference between native DOM elements and jQuery-wrapped elements within the callback, and how to break or continue loops early.

Basic Syntax

To loop through a collection of elements, call .each() directly on a jQuery object and pass a callback function.

$(selector).each(function(index, element) {
    // Code to run on each element
});
  • index (integer): The zero-based position of the current element in the collection.
  • element (DOM element): The current raw DOM element (equivalent to this).

Accessing Elements in the Loop

Inside the callback function, you can interact with the current element using either standard JavaScript or jQuery methods.

By default, both the element parameter and this refer to the native DOM element. To use jQuery methods such as .text(), .css(), or .addClass(), wrap the element in jQuery:

$('li').each(function(index, element) {
    // Using raw DOM properties
    console.log("Item " + index + ": " + this.id);

    // Using jQuery methods by wrapping with $()
    $(this).addClass('processed');
});

Example: Modifying Multiple Elements

Here is a practical example showing how to update text and styles across a list of items:

<ul>
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>
$('ul li').each(function(index) {
    var updatedText = (index + 1) + ": " + $(this).text();
    $(this).text(updatedText);
});

Breaking and Continuing the Loop

Unlike a standard JavaScript for loop, you cannot use the break or continue keywords inside a .each() callback. Instead, use boolean return values:

  • Break the loop: Return false to immediately stop all further iterations.
  • Continue to the next iteration: Return true (or simply return;) to skip the rest of the current iteration and proceed to the next element.
$('.items').each(function(index) {
    if ($(this).hasClass('skip')) {
        return true; // Skip to next item (continue)
    }

    if ($(this).hasClass('stop')) {
        return false; // Exit the loop entirely (break)
    }

    $(this).fadeIn();
});

jQuery Object Method vs. Generic Utility

Be aware that jQuery offers two different .each() methods:

  1. $(selector).each(function(index, element) {}): Operates specifically on a matched set of DOM elements in a jQuery object.
  2. $.each(collection, function(indexOrKey, value) {}): A generic utility function that can iterate over native JavaScript arrays, plain objects, or collections.