What Does 'this' Mean in jQuery? Explained: When and How to Use It

If you’ve spent any time working with jQuery, you’ve likely encountered the keyword this. It’s everywhere in jQuery code—from event handlers to loop iterations—but its behavior can be confusing, especially for developers new to JavaScript or jQuery. Is this a DOM element? A jQuery object? Or something else entirely?

In this guide, we’ll demystify this in jQuery. We’ll start by revisiting how this works in plain JavaScript (since jQuery builds on this foundation), then dive into how jQuery repurposes this in its methods. We’ll clarify the critical difference between this and $(this), explore common use cases, highlight mistakes to avoid, and even touch on advanced scenarios. By the end, you’ll confidently wield this in your jQuery projects.

Table of Contents#

  1. A Quick Refresher: this in Plain JavaScript
  2. What is this in jQuery?
  3. this vs. $(this): The Critical Difference
  4. Common Scenarios for Using this in jQuery
  5. Common Mistakes with this in jQuery
  6. Advanced Use Cases
  7. Summary
  8. References

1. A Quick Refresher: this in Plain JavaScript#

Before diving into jQuery, let’s recap how this works in vanilla JavaScript. The value of this depends on how a function is called (its execution context), not where it’s defined. Here are the most common scenarios:

  • Global context: In the global scope (outside any function), this refers to the global object (window in browsers, global in Node.js).

    console.log(this === window); // true (in browsers)
  • Function context: Inside a standalone function, this also refers to the global object (or undefined in strict mode).

    function myFunction() {
      console.log(this === window); // true (non-strict mode)
    }
    myFunction();
  • Object method: When a function is called as a method of an object, this refers to the object itself.

    const myObj = {
      name: "jQuery",
      greet: function() {
        console.log(`Hello, ${this.name}!`); // "Hello, jQuery!"
      }
    };
    myObj.greet(); // `this` = myObj
  • Constructor function: When using new to create an instance, this refers to the new object being created.

    function Person(name) {
      this.name = name; // `this` = new Person instance
    }
    const person = new Person("Alice");
    console.log(person.name); // "Alice"
  • Event handlers (native JS): In native JavaScript event handlers, this refers to the DOM element that triggered the event.

    <button onclick="console.log(this)">Click me</button>
    <!-- Logs the <button> DOM element when clicked -->

2. What is this in jQuery?#

jQuery builds on JavaScript’s this behavior but standardizes its meaning in most jQuery methods. In jQuery, this almost always refers to the raw DOM element (not a jQuery object) in the context of event handlers, loop iterations (e.g., .each()), and most jQuery method callbacks.

This is intentional: jQuery aims to simplify DOM manipulation, and this gives you direct access to the underlying DOM node, while wrapping it in $() converts it into a jQuery object (more on that later).

3. this vs. $(this): The Critical Difference#

The single most important distinction to understand is between this and $(this):

this$(this)
Raw DOM element (node)jQuery object wrapping the DOM element
Use native JS methodsUse jQuery methods

Example: Accessing an Attribute#

<button class="btn" id="myButton">Click Me</button>
// Using `this` (native JS)
$('.btn').click(function() {
  console.log(this.id); // "myButton" (native JS property)
});
 
// Using `$(this)` (jQuery)
$('.btn').click(function() {
  console.log($(this).attr('id')); // "myButton" (jQuery method)
});

Example: Modifying Styles#

// Using `this` (native JS)
$('.btn').click(function() {
  this.style.backgroundColor = 'blue'; // Native JS style property
});
 
// Using `$(this)` (jQuery)
$('.btn').click(function() {
  $(this).css('background-color', 'blue'); // jQuery .css() method
});

Key Takeaway: Use this for native DOM properties/methods (e.g., this.id, this.innerHTML) and $(this) for jQuery methods (e.g., $(this).attr(), $(this).html()).

4. Common Scenarios for Using this in jQuery#

Event Handlers (e.g., click, hover)#

In jQuery event handlers (e.g., .click(), .hover(), .on('click', ...)), this refers to the DOM element that triggered the event.

Example: Changing Text on Click

<ul class="todo-list">
  <li>Learn jQuery</li>
  <li>Master `this`</li>
</ul>
$('.todo-list li').click(function() {
  // `this` = the clicked <li> DOM element
  $(this).text('✅ ' + $(this).text()); // Add checkmark using jQuery
  this.style.color = 'green'; // Change color with native JS
});

When you click an <li>, this is the specific <li> that was clicked, and $(this) lets you use jQuery methods to modify it.

The .each() Method#

The .each() method iterates over a jQuery collection (e.g., $('div')). In its callback function, this refers to the current DOM element in the iteration.

Example: Logging List Items

<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ul>
$('ul li').each(function(index) {
  // `this` = current <li> DOM element
  const text = this.textContent; // Native JS
  console.log(`Index ${index}: ${text}`); 
  // Output: "Index 0: Apple", "Index 1: Banana", "Index 2: Cherry"
});

Method Chaining and Context#

jQuery’s method chaining (e.g., $('div').addClass('active').css('color', 'red')) works because most jQuery methods return the jQuery object. However, this inside method callbacks still refers to the DOM element.

Example: Chaining with .filter()

<div class="box" data-size="small">Small</div>
<div class="box" data-size="large">Large</div>
<div class="box" data-size="small">Small</div>
$('.box').filter(function() {
  // `this` = current .box DOM element
  return $(this).data('size') === 'small'; // Filter small boxes
}).css('background-color', 'lightblue'); // Apply style to filtered boxes

Here, .filter() uses this to check each .box DOM element, and the chained .css() applies to the filtered jQuery collection.

5. Common Mistakes with this in jQuery#

Mistake 1: Forgetting to Wrap this in $()#

A frequent error is calling jQuery methods directly on this, which is a DOM element, not a jQuery object.

$('.btn').click(function() {
  this.css('color', 'red'); // ❌ Error: this.css is not a function
  $(this).css('color', 'red'); // ✅ Correct: $(this) is a jQuery object
});

Mistake 2: Assuming this is a jQuery Object#

Conversely, using native JS methods on $(this) (a jQuery object) will fail:

$('.btn').click(function() {
  $(this).innerHTML = 'Clicked'; // ❌ Error: $(this).innerHTML is undefined
  this.innerHTML = 'Clicked'; // ✅ Correct: this is a DOM element
  $(this).html('Clicked'); // ✅ Also correct: jQuery .html() method
});

Mistake 3: Using this Outside Event Handlers/Loops#

this depends on context. Outside of event handlers, .each(), or jQuery callbacks, this may refer to the global object (window) or another context.

// ❌ `this` refers to `window` here (not a DOM element)
const myFunction = function() {
  console.log(this); // Window object
};
myFunction();
 
// ✅ `this` refers to the clicked element here
$('.btn').click(myFunction); // Logs the button DOM element

Mistake 4: Confusing this with Other Variables#

Avoid reassigning this to variables like self or that unless necessary (e.g., in nested functions). If you do, be consistent:

$('.btn').click(function() {
  const self = this; // Store `this` for use in nested functions
  setTimeout(function() {
    $(self).text('Delayed Click!'); // `this` here would be `window`, so use `self`
  }, 1000);
});

6. Advanced Use Cases#

Using this with Custom jQuery Plugins#

When building jQuery plugins, this refers to the jQuery object the plugin is called on. You can iterate over the elements using .each() and access individual DOM elements with this:

$.fn.highlight = function(color) {
  return this.each(function() {
    // `this` = current DOM element in the jQuery collection
    $(this).css('background-color', color);
  });
};
 
// Usage: Highlight all <p> elements yellow
$('p').highlight('yellow');

Changing this Context with .call()/.apply()#

You can override this in jQuery callbacks using JavaScript’s .call() or .apply() methods, though this is rarely needed:

const customContext = { message: "Custom context!" };
 
$('.btn').click(function() {
  console.log(this.message); // "Custom context!" (instead of the button)
}.call(customContext)); // Force `this` to be `customContext`

7. Summary#

  • this in jQuery refers to the raw DOM element in event handlers, .each() loops, and most jQuery callbacks.
  • $(this) wraps the DOM element in a jQuery object, enabling jQuery methods (e.g., .css(), .attr()).
  • Use this for native JS properties/methods (e.g., this.id, this.innerHTML).
  • Use $(this) for jQuery methods (e.g., $(this).attr('id'), $(this).html()).
  • Common mistakes: Forgetting to wrap this in $(), assuming this is a jQuery object, or using this outside the correct context.

8. References#

By mastering this and $(this), you’ll write cleaner, more effective jQuery code and avoid common pitfalls. Happy coding! 🚀