jQuery each() Method

The each() method loops over a set of elements or array items and runs a function for every single one. It is jQuery's primary tool for iteration — the equivalent of JavaScript's for loop, but designed for jQuery objects and arrays.

Two Forms of each()

// Form 1: Instance method — loops over matched elements
$(selector).each(function(index, element) { ... });

// Form 2: Static utility — loops over arrays or objects
$.each(arrayOrObject, function(key, value) { ... });

Form 1: Looping Over DOM Elements

$(document).ready(function() {
    $("li").each(function(index, element) {
        console.log("Item " + index + ": " + $(element).text());
    });
});

Inside the callback, index is the zero-based position. element is the raw DOM node — wrap it in $() to use jQuery methods on it. You can also use $(this), which refers to the same element.

Diagram: each() Over DOM Elements

  HTML: <ul>
          <li>Apple</li>
          <li>Banana</li>
          <li>Cherry</li>
        </ul>

  $("li").each(function(index) {
      // Call 1: index=0, $(this).text()="Apple"
      // Call 2: index=1, $(this).text()="Banana"
      // Call 3: index=2, $(this).text()="Cherry"
  });

Practical: Numbering List Items

$(document).ready(function() {
    $("li").each(function(index) {
        var currentText = $(this).text();
        $(this).text((index + 1) + ". " + currentText);
    });
});
// Result: "1. Apple", "2. Banana", "3. Cherry"

Practical: Highlight Cells Below a Threshold

$(document).ready(function() {
    $("td.score").each(function() {
        var score = parseInt($(this).text());
        if (score < 50) {
            $(this).css("background", "#ffcccc").css("font-weight", "bold");
        }
    });
});

Form 2: $.each() Over Arrays

var fruits = ["Apple", "Banana", "Cherry", "Dates"];

$.each(fruits, function(index, value) {
    console.log(index + " → " + value);
});

// Output:
// 0 → Apple
// 1 → Banana
// 2 → Cherry
// 3 → Dates

$.each() Over Objects

var person = { name: "Ravi", age: 28, city: "Mumbai" };

$.each(person, function(key, value) {
    console.log(key + ": " + value);
});

// Output:
// name: Ravi
// age: 28
// city: Mumbai

Practical: Build HTML from JSON Data

var employees = [
    { name: "Priya", dept: "Dev" },
    { name: "Arjun", dept: "Design" },
    { name: "Meena", dept: "HR" }
];

$(document).ready(function() {
    $.each(employees, function(i, emp) {
        var row = "<tr><td>" + (i + 1) + "</td>" +
                  "<td>" + emp.name + "</td>" +
                  "<td>" + emp.dept + "</td></tr>";
        $("#empTable tbody").append(row);
    });
});

Stopping each() Early with return false

Inside the callback, returning false works like a break statement — it stops the loop immediately.

$("li").each(function(index) {
    if ($(this).text() === "Cherry") {
        console.log("Found Cherry at index " + index);
        return false;   // stops the loop here
    }
});

Diagram: return false Stops the Loop

  Items: Apple (0), Banana (1), Cherry (2), Dates (3)

  Loop runs:
  index=0 → Apple   → continue
  index=1 → Banana  → continue
  index=2 → Cherry  → return false → LOOP STOPS
  index=3 → Dates   → never reached

each() vs jQuery Action on All Elements

jQuery applies methods to all matched elements automatically — you often do not need each(). Use each() when the action depends on each element's individual content or position.

// No each() needed — jQuery handles all elements:
$("p").css("color", "blue");

// each() needed — action depends on each element's value:
$("p").each(function(index) {
    if (index % 2 === 0) {
        $(this).css("color", "blue");
    } else {
        $(this).css("color", "red");
    }
});

Quick Summary

  • $(selector).each(fn) loops over matched DOM elements.
  • $.each(collection, fn) loops over arrays or plain objects.
  • Inside the callback, use $(this) or the element argument to access the current item.
  • Return false inside the callback to stop the loop early.
  • Use each() when each iteration needs its own unique logic based on position or content.

Leave a Comment

Your email address will not be published. Required fields are marked *