← Back to Chapters

jQuery each() Method

? jQuery each() Method

? Quick Overview

The 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.

? Interactive Demo

Click the button to use each() to style these items based on their index.

  • Item 0
  • Item 1
  • Item 2
  • Item 3

? Key Concepts

  • Iterates over matched DOM elements
  • Works with arrays and objects
  • Provides index and current value
  • this refers to the current element
  • Loop can be stopped using return false

? Syntax / Theory

? View Code Example
// General syntax of jQuery each()
$(selector).each(function(index, element){
// index  -> position of element
// element -> current DOM element
});

? Example 1: Loop Through DOM Elements

? View Code Example
// Iterate through list items and log index & text
$("li").each(function(index){
console.log("Index:", index);
console.log("Text:", $(this).text());
});

? Example 2: Using each() with Arrays

? View Code Example
// Loop through an array using jQuery each()
var colors = ["red","green","blue"];

$.each(colors, function(index, value){
console.log(index + " => " + value);
});

? Example 3: Using each() with Objects

? View Code Example
// Loop through object properties
var user = {
name: "Alex",
age: 22,
role: "Student"
};

$.each(user, function(key, value){
console.log(key + ": " + value);
});

? Live Output / Explanation

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.

? Interactive Example: Styling Elements

? View Code Example
// Apply alternating background colors using each()
$("p").each(function(index){
if(index % 2 === 0){
$(this).css("background","#e0f2fe");
}else{
$(this).css("background","#fef3c7");
}
});

? Use Cases

  • Bulk DOM styling and manipulation
  • Validating multiple form fields
  • Extracting data from tables
  • Applying conditional logic to elements
  • Processing JSON data

✅ Tips & Best Practices

  • Use this instead of re-selecting elements
  • Use return false to break the loop early
  • Avoid complex logic inside each()
  • Prefer native loops for performance-critical code

? Try It Yourself

  • Highlight table rows using each()
  • Disable all empty input fields
  • Count checked checkboxes
  • Create a dynamic list highlighter