๐ 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
Mistake | Fix |
---|---|
Using this instead of $(this) | Wrap this in $() to use jQuery methods |
Not breaking the loop when needed | Use return false; |
Forgetting index/value in object loop | key, value is the correct order for objects |
๐ง Real-World Use Cases
Scenario | Purpose |
---|---|
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 :