Lesson 18: jQuery Looping with each()

Master jQuery looping techniques with the each() method. Learn to iterate through collections with practical examples and interactive demos.

Understanding jQuery Looping

The jQuery each() method provides a powerful way to iterate through collections of elements, arrays, and objects. It's essential for performing operations on multiple elements efficiently.

Key Looping Concepts:
  • each() - Iterates over a jQuery object, executing a function for each matched element
  • $.each() - A generic iterator for arrays and objects
  • this keyword - Refers to the current DOM element within the loop
  • index parameter - Provides the current iteration index
  • return false - Breaks out of the loop early
Method Description Example
each() Iterates over jQuery objects $("li").each(function() { ... })
$.each() Iterates over arrays and objects $.each(myArray, function(index, value) { ... })

Basic each() Usage

The most common use of each() is to iterate through a collection of DOM elements and perform operations on each one.

Example 18.1: Looping Through List Items

Add numbers and colors to each list item:

  • First Item
  • Second Item
  • Third Item
  • Fourth Item
  • Fifth Item
// each() method examples
$("#number-items").click(function() {
    $("#list1 li").each(function(index) {
        $(this).text((index + 1) + ". " + $(this).text());
    });
});

$("#color-items").click(function() {
    const colors = ["#4CAF50", "#2196F3", "#FF9800", "#9C27B0", "#F44336"];
    
    $("#list1 li").each(function(index) {
        $(this).css("background-color", colors[index]);
        $(this).css("color", "white");
    });
});

$("#reset-items").click(function() {
    $("#list1 li").each(function() {
        $(this).text($(this).text().replace(/^\d+\.\s/, ""));
        $(this).css("background-color", "white");
        $(this).css("color", "#333");
    });
});

Working with Index and Element

The each() callback function receives two parameters: the current index and the current element.

Example 18.2: Using Index and Element

Create a multiplication table using each():

Multiplier × 1 × 2 × 3 × 4 × 5
// Using index and element
$("#generate-table").click(function() {
    $("#table-body").empty();
    
    // Create rows
    for (let i = 1; i <= 5; i++) {
        const row = $("<tr>");
        
        // Create multiplier cell
        $("<td>").text(i).appendTo(row);
        
        // Create product cells
        for (let j = 1; j <= 5; j++) {
            $("<td>").text(i * j).appendTo(row);
        }
        
        $("#table-body").append(row);
    }
    
    // Apply styles to each row
    $("#table-body tr").each(function(index) {
        if (index % 2 === 0) {
            $(this).css("background-color", "#e3f2fd");
        }
    });
});

$("#clear-table").click(function() {
    $("#table-body").empty();
});

Breaking Loops Early

You can break out of an each() loop prematurely by returning false from the callback function.

Example 18.3: Breaking Loops

Find the first item matching a condition:

Results will appear here
// Breaking loops with return false
$("#find-item").click(function() {
    const searchValue = parseInt($("#search-value").val());
    let found = false;
    let result = "Searching for: " + searchValue + "<br>";
    
    // Generate random numbers
    const numbers = [];
    for (let i = 0; i < 20; i++) {
        numbers.push(Math.floor(Math.random() * 100) + 1);
    }
    
    result += "Numbers: " + numbers.join(", ") + "<br><br>";
    
    // Search using each()
    $.each(numbers, function(index, value) {
        if (value === searchValue) {
            result += "Found at position: " + (index + 1);
            found = true;
            return false; // Break the loop
        }
    });
    
    if (!found) {
        result += "Value not found!";
    }
    
    $("#search-result").html(result);
});

$("#reset-search").click(function() {
    $("#search-result").text("Results will appear here");
});

Iterating Objects with $.each()

The $.each() method can iterate through both arrays and objects, making it extremely versatile.

Example 18.4: Iterating Objects

Display user information from an object:

User information will appear here
// Iterating objects with $.each()
$("#display-users").click(function() {
    const users = {
        "user1": { "name": "Alice", "age": 28, "role": "Developer" },
        "user2": { "name": "Bob", "age": 32, "role": "Designer" },
        "user3": { "name": "Charlie", "age": 25, "role": "Manager" },
        "user4": { "name": "Diana", "age": 40, "role": "Director" }
    };
    
    let output = "<div class='user-list'>";
    
    $.each(users, function(key, user) {
        output += "<div class='user-item'>" +
                  "<h4>" + user.name + "</h4>" +
                  "<p>Age: " + user.age + "</p>" +
                  "<p>Role: " + user.role + "</p>" +
                  "</div>";
    });
    
    output += "</div>";
    $("#user-result").html(output);
});

$("#clear-users").click(function() {
    $("#user-result").text("User information will appear here");
});

Practical Applications

jQuery looping is essential for many common web development tasks:

Dynamic Tables

Generate and manipulate table data efficiently.

Form Processing

Validate or collect data from multiple form fields.

Data Visualization

Process data for charts and graphs.

Filtering Content

Iterate through elements to show/hide based on criteria.

Looping Playground

Experiment with different looping techniques:

Card 1
Card 2
Card 3
Card 4
Card 5
Loop results will appear here
// Looping Playground
$("#run-loop").click(function() {
    const loopType = $("#loop-type").val();
    let result = "";
    
    $(".content-card").each(function(index, element) {
        const $card = $(this);
        const id = $card.data("id");
        
        switch(loopType) {
            case "simple":
                $card.css("background-color", "#4CAF50");
                result += "Processed card " + id + "<br>";
                break;
                
            case "index":
                const colors = ["#2196F3", "#FF9800", "#9C27B0", "#F44336", "#4CAF50"];
                $card.css("background-color", colors[index]);
                result += "Card " + id + " - index: " + index + "<br>";
                break;
                
            case "conditional":
                if (id % 2 === 0) {
                    $card.css("background-color", "#FF9800");
                    result += "Card " + id + " (even) processed<br>";
                } else {
                    $card.css("background-color", "#2196F3");
                    result += "Card " + id + " (odd) processed<br>";
                }
                break;
                
            case "break":
                if (id > 3) {
                    result += "Breaking loop at card " + id + "<br>";
                    return false; // Break loop
                }
                $card.css("background-color", "#9C27B0");
                result += "Processed card " + id + "<br>";
                break;
        }
    });
    
    $("#loop-result").html(result);
});

$("#reset-playground").click(function() {
    $(".content-card").css("background-color", "#2196F3");
    $("#loop-result").text("Loop results will appear here");
});

Best Practices

Follow these guidelines when working with jQuery looping:

  • Cache your selectors - Store jQuery objects in variables to avoid requerying the DOM
  • Use native loops for arrays - For simple array operations, JavaScript's native for/forEach may be faster
  • Minimize DOM manipulation - Batch changes when possible to improve performance
  • Use break and continue - Return false to break, return true to continue to next iteration
  • Consider performance - For large collections, consider alternative approaches
// Best practices for jQuery looping

// 1. Cache selectors
const $items = $(".item");
$items.each(function() {
    // Work with each item
});

// 2. Use native loops for arrays
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
    console.log(number);
});

// 3. Batch DOM manipulations
let fragment = document.createDocumentFragment();
$items.each(function() {
    const newElement = document.createElement("div");
    // Configure element...
    fragment.appendChild(newElement);
});
$("#container").append(fragment);

// 4. Using break and continue
$items.each(function(index) {
    if (index === 3) return false; // Break loop
    if (index === 1) return true;  // Continue to next iteration
    // Process item
});