5

I am reading a jQuery book and sometimes I see the example like:

$('img[alt]').each(function(){
  $(this).replaceWith('<span>' + $(this).attr('alt')+ '</span>')
}

and sometimes I see examples like:

$('*').attr('title', function(index, value) {
return value + 'I am element ' + index + ' and my name is ' + this.id);
});

so see sometimes it is $(this) and sometimes it is just this

What's the difference? How do I know which one to use and when?

Jude Duran
  • 2,195
  • 2
  • 25
  • 41

6 Answers6

7

Use this if you want to directly access the DOM node that's being processed. It's the default context in any jQuery-registered event handler (i.e. the element that received the event) and many other jQuery functions such as .each.

Use $(this) if you want to call a jQuery method on that element.

Use var $this = $(this) if you expect to call lots of jQuery methods on the element, where in my own coding style "lots" is "any more than one".

In many cases it's better to use plain this - I consider writing $(this).attr('id') instead of this.id an anti-pattern.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
5

this is DOM element

$(this) is jquery object

so with $(this) you can use all the methods of jquery like attr(),val().. where as we cannot with this.. you have to use this.value or this.id

bipen
  • 36,319
  • 9
  • 49
  • 62
3

$(this) is wrapping this in a jquery selector.

Often this is done when thisrefers to a DOM element and you wish to use the jQuery computational model on that element. E.g. in a callback. If the attribute you are looking for is part of the DOM model and consistent across browsers like the id attribute is then there's no need to wrap this in a jQuery selector you can simply do this.id where the jQuery version would be $(this).attr('id')

Side note this in both cases points to the same object but in the case of $(this) that object is passed as an argument to the function named $

Rune FS
  • 21,497
  • 7
  • 62
  • 96
1

At first case we represent it for an DOM element and in second it is the object of that element and

$(this)[0] = this;
GautamD31
  • 28,552
  • 10
  • 64
  • 85
1

this refers to the DOM element itself; $(this) wraps the element up in a jQuery object.

PSR
  • 39,804
  • 41
  • 111
  • 151
1

'this' is a jQuery object when you are inside your own jQuery functions. Note that the result of a selector query (i.e. $(this) ) is a jQuery object, which is an array of the matched DOM elements

Reference

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307