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.
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");
}
});
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);
});
$(this) to turn the current element into a jQuery object, allowing you to
use methods like .attr() or .hide().
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());
});
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);
});
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.
each() for complex tasks.