jQuery .each() Method โ€“ Loop Through Elements and Data Easily


Introduction โ€“ Why Use jQuery .each()?

When working with multiple DOM elements, arrays, or objects in jQuery, the .each() method allows you to iterate through each item and perform an actionโ€”without needing a for or while loop. It simplifies operations like batch styling, value retrieval, and data display in a cleaner, chainable, and more readable way.

In this guide, you’ll learn:

  • How .each() works for DOM elements and JavaScript objects
  • Syntax differences between $.each() and $(selector).each()
  • Real-world examples for manipulating lists, tables, and datasets
  • Common pitfalls and best practices

Basic Syntax

For jQuery Selections:

$(selector).each(function(index, element) {
  // Your code here
});

For Arrays/Objects (Global Utility):

$.each(arrayOrObject, function(index, value) {
  // Your code here
});

Example 1 โ€“ Loop Through Elements with $(selector).each()

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>jQuery</li>
</ul>

<script>
  $("li").each(function(index) {
    console.log("Item " + index + ": " + $(this).text());
  });
</script>

Explanation:

  • Selects all <li> elements
  • Logs each oneโ€™s index and text
  • $(this) refers to the current element being looped

Ideal for styling, data gathering, or batch modifications.


Example 2 โ€“ Loop Through Array with $.each()

let colors = ["red", "green", "blue"];

$.each(colors, function(i, color) {
  console.log(i + " โ†’ " + color);
});

Explanation:

  • Loops through the array
  • i is the index, color is the value at that index

Great for processing raw arrays or JSON lists.


Example 3 โ€“ Loop Through Object with $.each()

let user = { name: "Alice", age: 25, country: "India" };

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

Simple way to loop over key-value pairs in an object.


Example 4 โ€“ Use .each() to Set Styles Dynamically

$(".box").each(function(i) {
  $(this).css("background-color", i % 2 === 0 ? "lightblue" : "lightgray");
});

Alternates background color of boxes for a striped layout effect.


How to Exit a Loop Early

Use return false; to break the loop (like break in regular loops):

$("li").each(function(i) {
  if (i === 2) return false; // stops after 3rd item
});

.each() vs Native forEach()

Feature.each().forEach()
jQuery elements Yes No (requires conversion)
Works on objects Yes No (only arrays)
Return false to break Supported Unsupported (must use some() or every())

Best Practices

Use $(this) inside .each() to refer to the current element
Prefer $.each() for looping through JSON, arrays, and objects
Use .eq(index) sparingly inside .each() โ€” itโ€™s slower than using this
Always use return false; to break early and return true; to continue if needed


Common Pitfalls

MistakeFix
Using this instead of $(this)Wrap this in $() to use jQuery methods
Not breaking the loop when neededUse return false;
Forgetting index/value in object loopkey, value is the correct order for objects

Real-World Use Cases

ScenarioPurpose
Highlight menu items.each() to add styles or icons
Parse JSON API results$.each() to build cards/lists
Collect form field values.each() with input/select
Apply alternating row styles.each() with i % 2 logic
Map data to charts or lists$.each() with data processing

Summary โ€“ Recap & Next Steps

The jQuery .each() method is an elegant, cross-compatible way to loop over elements, arrays, and objects with ease. Whether youโ€™re building dynamic layouts, parsing data, or processing input, .each() keeps your code clean and chainable.

Key Takeaways:

  • Use $(selector).each() for DOM elements
  • Use $.each() for arrays and objects
  • Use $(this) for manipulating the current element
  • Use return false to break out of the loop early

Real-World Relevance:
Used extensively in data rendering, dynamic UI updates, AJAX response parsing, and plugin development.


FAQ โ€“ jQuery .each() Method

Whatโ€™s the difference between $.each() and .each()?

$.each() is for arrays/objects
.each() is for jQuery selections (DOM elements)


How do I stop a .each() loop early?

Use:

return false;

Can I get the index of the current element?

Yes:

$(selector).each(function(index) {
  console.log(index);
});

Can I use break or continue in .each()?

No native break; use return false (to break) or return true (to continue).


Can .each() be chained?

Yes, it returns the original jQuery object:

$("li").each(...).addClass("processed");

Share Now :
Share

๐Ÿ” jQuery each() Method

Or Copy Link

CONTENTS
Scroll to Top