HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery each() Method

Written by RedoHub Team · Last updated: August 1, 2026

The each() method is jQuery's answer to the traditional for or forEach loop. It provides an easy way to iterate over both jQuery collections (DOM elements) and generic JavaScript objects or arrays.


1. Looping through DOM Elements

When used on a jQuery selector, each() runs a function for every single matched element.

$("li").each(function(index) {
    // 'index' is the position (0, 1, 2...)
    // 'this' refers to the current DOM element
    console.log("Item " + index + " text: " + $(this).text());
    
    // You can add styles or logic to each one
    if(index % 2 === 0) {
        $(this).css("color", "red");
    }
});

2. Looping through Arrays and Objects

You can also use the $.each() utility method to loop through non-jQuery data like arrays or JSON objects.

// Looping through an Array
var fruits = ["Apple", "Banana", "Orange"];
$.each(fruits, function(index, value) {
    alert(index + ": " + value);
});

// Looping through an Object
var user = { name: "John", age: 30, city: "Paris" };
$.each(user, function(key, value) {
    console.log(key + " is " + value);
});
Context Tip: Inside the callback function, you can use $(this) to turn the current element into a jQuery object, allowing you to use methods like .attr() or .hide().

Breaking out of a Loop

Similar to the break statement in a normal loop, you can stop a jQuery each() loop early by returning false in your callback function.

$("li").each(function() {
    if ($(this).text() === "Stop Here") {
        return false; // Loop stops immediately
    }
    console.log($(this).text());
});

Practical Example: Form Summary

You can use each() to collect values from all input fields to create a quick preview before submission.

$("#previewBtn").click(function() {
    var summary = "Your details: ";
    
    // Loop through every text input in the form
    $("form input[type='text']").each(function() {
        summary += $(this).val() + ", ";
    });
    
    $("#previewArea").text(summary);
});
Pro Tip: If you only need to change a CSS property or an attribute for all elements, you don't need each(). jQuery's **implicit iteration** handles it automatically: $("p").css("color", "red") styles all paragraphs at once! Only use each() when you need custom logic for each item.

Key Points to Remember

  • each() is used for both DOM elements and data iteration.
  • The callback function provides index/key and value parameters.
  • $(this) is the most common way to target the current item in the loop.
  • Returning false breaks the loop; returning true continues it (like `continue`).
  • Most jQuery methods use implicit iteration, so you only need each() for complex tasks.

Common Mistakes to Avoid

Confusing the argument order in $.each() for arrays vs. objects. For both, the callback receives (index/key, value) — but it's easy to assume arrays pass (value, index) like Array.prototype.forEach does. They don't; jQuery is consistent with (key, value) either way.
Using return false; expecting it to skip just one iteration. Returning false stops the entire loop immediately, not just the current item. To skip an item and continue, return nothing (or true) or use a plain continue in a real loop instead.
Reaching for .each() when implicit iteration already applies the action. $("p").addClass("x") already applies to every matched paragraph — wrapping it in .each() is unnecessary and slower.

Try It: Building a Total from Input Values

A second example — using each() to sum up numeric values from several inputs on the page:

<input type="number" class="price" value="10">
<input type="number" class="price" value="25">
<input type="number" class="price" value="15">
<button id="totalBtn">Calculate Total</button>
<p id="totalOutput"></p>

<script>
    $(function() {
        $("#totalBtn").click(function() {
            var total = 0;
            $(".price").each(function() {
                total += Number($(this).val());
            });
            $("#totalOutput").text("Total: " + total);
        });
    });
</script>

Frequently Asked Questions

Q: What's the difference between .each() and $.each()?

A: .each() is called on a jQuery selection to loop over matched DOM elements; $.each() is a standalone utility for looping over any array or plain object.

Q: Can I use a regular for loop instead of each()?

A: Yes — each() is a convenience, not a requirement. A plain for loop over $("li").get() (the raw DOM array) works too.

Q: Does each() work on nested arrays or objects?

A: It only iterates one level deep — for nested structures, call $.each() again inside the callback. See the official $.each() documentation for edge cases.