Understanding 'this' Scope in jQuery .each()
Inside a jQuery .each() loop, the this
keyword refers directly to the current native DOM element in the
iteration. While this provides immediate access to standard JavaScript
DOM properties and methods, developers frequently wrap it as
$(this) to utilize jQuery's built-in methods. Understanding
the scope of this—and how modern JavaScript features like
arrow functions alter its behavior—is essential for writing clean,
bug-free DOM manipulation scripts.
The Standard Behavior of
this
When iterating over a collection using standard function syntax,
jQuery explicitly binds the execution context (this) to the
current DOM element being processed.
$('li').each(function() {
// 'this' refers to the raw HTML DOM element (e.g., <li>)
console.log(this.id);
});Because this is a raw DOM node, you have native access
to its properties, such as this.id,
this.value, or this.className. Standard DOM
methods like this.getAttribute() also work directly.
Native DOM
Element vs. jQuery Object: this vs
$(this)
A common source of confusion is the distinction between
this and $(this):
this: Represents the raw DOM node. jQuery methods (such as.hide(),.addClass(), or.attr()) will not work directly onthis. Callingthis.addClass('active')will throw aTypeError.$(this): Wraps the native DOM element into a new jQuery object, enabling the use of jQuery's chaining and utility methods.
$('li').each(function() {
// Native JavaScript
this.style.color = 'red';
// jQuery method
$(this).addClass('highlighted');
});Callback Parameters as an Alternative
The callback function in .each() accepts two parameters:
index and element. The element
parameter points to the exact same DOM node as this.
$('li').each(function(index, element) {
console.log(this === element); // Returns true
});Using the explicit element parameter is often preferred
for readability, especially in nested loops where this
changes context.
The Impact of ES6 Arrow Functions
If you use an ES6 arrow function inside .each(), the
behavior of this changes completely. Arrow functions do not
bind their own this; instead, they lexically capture the
this value of the enclosing execution context.
// Incorrect use of 'this' with arrow functions
$('li').each((index, element) => {
// 'this' does NOT point to the <li> element.
// It points to the outer scope (e.g., window or the surrounding object).
console.log(this);
// To access the current element, use the 'element' parameter instead:
$(element).addClass('active');
});When using arrow functions with jQuery's .each(), avoid
using this altogether and rely on the second callback
argument (element) to interact with the iterated item.