Skip to content

jQuery 'this' — Complete Guide to the Keyword in Event Handlers and Callbacks

DodaTech Updated 2026-06-28 6 min read

In this tutorial, you will learn about jquery 'this'. We cover key concepts, practical examples, and best practices to help you master this topic.

The jQuery 'this' keyword refers to the current DOM element in event handlers and callbacks, providing direct access to the element without a jQuery wrapper for better performance and clarity.

What You'll Learn

  • What 'this' refers to in different jQuery contexts
  • Converting 'this' to a jQuery object with $(this)
  • 'this' in event handlers, each loops, and callbacks
  • Arrow functions vs function expressions with 'this'
  • Common pitfalls and best practices

Why It Matters

Understanding 'this' is critical for correct jQuery code. Misunderstanding the context leads to bugs where you operate on the wrong element, call methods that do not exist, or get undefined errors.

Real-World Use

A table with editable cells. Clicking a cell highlights it, double-clicking makes it editable, and pressing Enter saves the value. Each handler uses 'this' to identify and manipulate the clicked cell without re-selecting it.

'this' Context Flow

flowchart TD
    A[Code Context] --> B{Where is this?}
    B -->|Event Handler| C[DOM Element]
    B -->|$.each callback| D[Current Array Item]
    B -->|$.each element| E[DOM Element]
    B -->|Method call| F[Object before dot]
    B -->|Arrow function| G[Outer Context]
    style C fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px

'this' in Event Handlers

In jQuery event handlers, this refers to the DOM element that received the event:

$('.item').on('click', function() {
  // 'this' is the clicked DOM element
  console.log(this);                    // <div class="item">...</div>
  console.log(this.tagName);           // DIV

  // Convert to jQuery object for jQuery methods
  $(this).addClass('active');
  $(this).css('background', '#3498db');
});

// Multiple events
$('input').on({
  focus: function() {
    $(this).addClass('focused');
  },
  blur: function() {
    $(this).removeClass('focused');
    validateField($(this));
  }
});

Expected output: In the click handler, this is the exact DOM element clicked. Wrapping with $(this) enables jQuery methods.

'this' vs $(this)

$('.item').click(function() {
  // 'this' — raw DOM element
  this.style.color = 'red';                    // Native JS (faster)
  console.log(this.id);                        // Native property access

  // $(this) — jQuery wrapper
  $(this).css('color', 'red');                 // jQuery method (convenient)
  $(this).addClass('highlight');
  $(this).data('key', 'value');

  // Mixing is fine, but be consistent within a handler
  var $el = $(this);  // Cache at start of handler
  $el.addClass('clicked');
  console.log($el.data('id'));
});

'this' in $.each()

In $.each(), this refers to the current element or value:

// Iterating an array
$.each(['apple', 'banana', 'cherry'], function(index, value) {
  console.log(this === value); // true — 'this' is the current value
  console.log(this);           // 'apple', then 'banana', then 'cherry'
});

// Iterating jQuery collection
$('.item').each(function(index) {
  // 'this' is the current DOM element
  console.log(this);                    // DOM element
  console.log($(this).text());          // Element's text

  // Store index as data
  $(this).data('index', index);
});

'this' in Callbacks

// Animation callback
$('.box').slideUp(400, function() {
  // 'this' is the animated DOM element
  $(this).css('display', 'none');
  console.log('Animation finished for', this.id);
});

// AJAX callback (depends on context option)
$.ajax({
  url: '/api/data',
  context: document.body,  // 'this' will be document.body
  success: function(data) {
    console.log(this === document.body); // true
    $(this).append('<p>Data loaded</p>');
  }
});

'this' in Arrow Functions

Arrow functions do NOT have their own this — they inherit from the enclosing scope:

// BAD: Arrow function changes 'this' context
$('.item').click(() => {
  // 'this' is NOT the DOM element — it's the outer scope (likely window)
  $(this).addClass('active'); // Wrong element!
});

// GOOD: Regular function expression
$('.item').click(function() {
  $(this).addClass('active'); // Correct — 'this' is the clicked element
});

// GOOD: Arrow function inside $.each (outer scope preserved)
var self = this;
$('.item').each(function() {
  // 'this' is the DOM element (regular function)
  // 'self' is the outer object
});

'this' in Custom Methods

var MyWidget = {
  init: function() {
    this.name = 'Widget';  // 'this' is MyWidget
    $('.btn').click(this.handleClick);
  },
  handleClick: function() {
    // 'this' is the DOM element (button), not MyWidget!
    console.log(this.name); // undefined
  }
};

// Fix: use $.proxy or bind
var MyWidget = {
  init: function() {
    this.name = 'Widget';
    $('.btn').click($.proxy(this.handleClick, this));
    // OR: $('.btn').click(this.handleClick.bind(this));
  },
  handleClick: function() {
    // 'this' is now MyWidget
    console.log(this.name); // Output: Widget
  }
};

// Modern fix: arrow function in the click handler
var MyWidget = {
  init: function() {
    this.name = 'Widget';
    $('.btn').click((e) => {
      // 'this' is MyWidget (arrow inherits from init's 'this')
      console.log(this.name); // Widget
      // For the DOM element, use e.target
      console.log(e.target);
    });
  }
};

'this' in Event Delegation

$('.list').on('click', '.item', function() {
  // 'this' is the .item element that was clicked
  // Not the .list container
  $(this).toggleClass('selected');
});

// Access the delegate (container)
$('.list').on('click', '.item', function(e) {
  var $item = $(this);
  var $list = $(e.delegateTarget); // The .list container
  var $relatedTarget = $(e.target); // The exact clicked element
});

Caching $(this) for Performance

// BAD: Re-wrapping $(this) multiple times
$('.item').click(function() {
  $(this).addClass('active');
  $(this).data('clicked', true);
  $(this).find('.child').toggle();
});

// GOOD: Cache $(this) once
$('.item').click(function() {
  var $this = $(this);
  $this.addClass('active');
  $this.data('clicked', true);
  $this.find('.child').toggle();
});

Common Mistakes

  1. Using arrow functions in event handlers - Arrow functions inherit this from the outer scope, not the DOM element. Always use function() for event handlers.

  2. Assuming 'this' in $.ajax success is the element - By default, this in AJAX callbacks is the Ajax settings object. Use context option or arrow functions.

  3. Forgetting to wrap 'this' for jQuery methods - this.addClass('active') throws an error because this is a DOM element, not a jQuery object. Use $(this).addClass().

  4. 'this' in nested callbacks - Inside a forEach, map, or setTimeout, this changes. Capture the outer this in a variable: var self = this.

  5. Confusing 'this' and event.target - this is the element the handler is bound to. event.target is the element that triggered the event. They differ in event delegation.

Practice Questions

  1. What does 'this' refer to inside a jQuery click handler?
  2. Why should you avoid arrow functions in jQuery event handlers?
  3. How do you convert 'this' to a jQuery object?
  4. What is the difference between 'this' and event.target?
  5. How do you preserve the outer 'this' inside a $.each loop?

Challenge: Build a tooltip plugin where hovering over any element with a data-tooltip attribute shows a tooltip. Use 'this' correctly in the hover handlers, cache $(this), and handle the tooltip positioning relative to 'this'.

FAQ

Does 'this' change in a setTimeout inside an event handler?

Yes. setTimeout creates a new execution context where 'this' defaults to window. Use $.proxy, bind, or an arrow function to preserve the context.

What is the difference between 'this' and '$(this)'?

'this' is the raw DOM element. '$(this)' wraps it in a jQuery object, giving access to jQuery methods. 'this' is faster but less convenient.

How do I access the element that triggered a delegated event?

Use 'this' for the matched element, 'e.target' for the exact clicked element, and 'e.delegateTarget' for the container.

Can I use 'this' in a jQuery plugin method?

Yes. In a jQuery plugin method, 'this' refers to the jQuery collection the method was called on. Return 'this' for chaining.

Why does 'this' in an AJAX callback not refer to the DOM element?

The AJAX callback runs in a different context. Use the context option in $.ajax settings to set 'this', or use an arrow function.

Mini Project

Build a drag-and-drop card game where clicking a card selects it, clicking another position moves it. Each handler uses 'this' to identify the clicked card. Cache $(this) at the start of each handler for performance.

What's Next

The 'this' keyword is fundamental. Learn how jQuery event handling uses 'this' to connect user interactions with element-specific logic.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro