4

When passing a context to the selector, is it better to pass this or $(this)? I tried the latter and it worked; the doc mentioned the former.

$('.link').on('click', function () {
  $('.element', this).addClass('something');
  // or, $('.element, $(this)).addClass('something'); ?
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
moey
  • 10,587
  • 25
  • 68
  • 112
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1051782/jquery-this-vs-this – Paul Grimshaw Sep 24 '12 at 12:48
  • 1
    It depends on the context that your are using `this`. If you are going to call a jQuery function, `$(this).hide()` you have to use $(this). If you just need to reference the given element you can use the plain `this`. In the context you have here `$(this)` is used no differently than `this`. In fact there is probably some (minimal) overhead to convert the element to a jQuery object and then reference the element inside the wrapper. – aknosis Sep 24 '12 at 15:50

1 Answers1

4

Use:

$(this).find('.element').addClass('something');

$('.element', this) will turn into $(this).find('.element') internal.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • @Aknosis Why? No matter you use `this` or `$(this)` as the second parameter, it will be turned into `$(this).find('.element')...` – xdazz Sep 24 '12 at 15:53
  • 1
    I guess you are right, I just read the source and they both equivalent in functionality. I was thinking more in terms of the this vs $(this) question, but in the context given it makes no difference whatsoever. – aknosis Sep 24 '12 at 17:31
  • 1
    From the source (1.8.2): `return this.constructor( context ).find( selector );` – moey Oct 02 '12 at 03:37