jQuery Each()

The jQuery each() method is used to iterate over a collection of elements or objects, performing an action for each matched element. It is especially useful when working with lists, arrays, or sets of elements.

Key Topics

Basic Usage of each()

The each() method loops through each element in a jQuery collection and applies a function.

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

Explanation: This code iterates through all <li> elements, logging their index and text content to the console.

Looping Through Objects

You can also use each() to iterate over JavaScript objects, performing an action on each key-value pair.

var data = { name: "John", age: 30, city: "New York" };
$.each(data, function(key, value) {
    console.log(key + ": " + value);
});

Explanation: This code iterates through the data object, logging each key-value pair to the console.

Example: Using each()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Each Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Cherry</li>
    </ul>
    <script>
        $(document).ready(function() {
            $("li").each(function(index, element) {
                console.log("Item " + index + ": " + $(element).text());
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to iterate through all <li> elements in an unordered list and log their index and text content to the console.

Key Takeaways

  • Iterating Elements: Use each() to loop through jQuery collections like lists or arrays.
  • Object Iteration: Apply each() to iterate through JavaScript objects and perform actions on their key-value pairs.
  • Dynamic Processing: Ideal for applying actions or retrieving data from multiple elements or objects.