HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery each() Method

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.