each() MethodThe each() method is one of the most important iteration utilities in jQuery. It allows you to loop through DOM elements, arrays, and objects efficiently while executing a callback function for every item.
Click the button to use each() to style these items based on their index.
this refers to the current elementreturn false
// General syntax of jQuery each()
$(selector).each(function(index, element){
// index -> position of element
// element -> current DOM element
});
// Iterate through list items and log index & text
$("li").each(function(index){
console.log("Index:", index);
console.log("Text:", $(this).text());
});
// Loop through an array using jQuery each()
var colors = ["red","green","blue"];
$.each(colors, function(index, value){
console.log(index + " => " + value);
});
// Loop through object properties
var user = {
name: "Alex",
age: 22,
role: "Student"
};
$.each(user, function(key, value){
console.log(key + ": " + value);
});
Each example prints values to the browser console. DOM iteration logs element index and content, array iteration logs values, and object iteration logs key–value pairs.
// Apply alternating background colors using each()
$("p").each(function(index){
if(index % 2 === 0){
$(this).css("background","#e0f2fe");
}else{
$(this).css("background","#fef3c7");
}
});
this instead of re-selecting elementsreturn false to break the loop earlyeach()each()