Difference Between jQuery .each() and $.each()
While both .each() and $.each() in jQuery
are used for iteration, they serve fundamentally different purposes
based on the data being processed. The .each() method is a
jQuery prototype method used exclusively to loop over DOM elements
within a jQuery collection. In contrast, $.each() is a
general utility function capable of iterating over any generic
JavaScript object or array. Understanding the distinction between these
two methods ensures cleaner, more efficient code and prevents common
selector errors.
The jQuery .each()
Method
The .each() method is chained directly onto a jQuery
selection. It is designed specifically to traverse the DOM elements
wrapped in that specific jQuery object.
- Syntax:
$(selector).each(function(index, element) { ... }) - Target: DOM elements matched by the selector.
- Context (
this): Inside the callback function, thethiskeyword refers to the current raw DOM element (not a jQuery object).
Example:
// Iterating over all <li> elements on the page
$('li').each(function(index, element) {
console.log(index + ': ' + $(element).text());
});In this case, the method automatically loops through every matching
<li> tag.
The jQuery $.each()
Function
The $.each() method (also written as
jQuery.each()) is a global utility function. It does not
require a DOM selection and can iterate over standard JavaScript arrays,
array-like objects, and key-value objects.
- Syntax:
$.each(collection, function(indexOrKey, value) { ... }) - Target: Any JavaScript array or plain object.
- Context (
this): Inside the callback,thisrefers to the current value being iterated over.
Example with an Array:
const colors = ['red', 'green', 'blue'];
$.each(colors, function(index, value) {
console.log(index + ': ' + value);
});Example with an Object:
const user = { name: 'Alice', age: 25, role: 'Admin' };
$.each(user, function(key, value) {
console.log(key + ': ' + value);
});Key Differences
| Feature | $(selector).each() |
$.each(collection, callback) |
|---|---|---|
| Type | jQuery instance method | Global utility function |
| Target Data | jQuery DOM element collections | Arrays, plain objects, or collections |
| Invocation | Chained to a jQuery object | Called directly via the $
namespace |
| Arguments | Takes only the callback function | Takes the collection first, then the callback |
| Primary Use Case | Manipulating or reading DOM nodes | General data processing and iteration |
When to Use Which
Use .each() when you have queried the DOM using a jQuery
selector and need to perform an action on each matched HTML element,
such as adding classes, modifying attributes, or binding events.
Use $.each() when working with raw data structures like
JSON responses, plain JavaScript arrays, or objects where DOM
interaction is not directly tied to the iteration source.