Anriëtte Myburgh
Anriëtte Myburgh

Reputation: 13517

What is most beneficial to use? $(this) vs. this

When is it most beneficial to use $(this) and when should I use the plain old this ($(this)[0])?

I have posted on SO before, where someone told me I shouldn't use $(this) so much in my function but rather this.

Why? Is $(this) rather memory intensive or something? Or does it sometimes contain more data than you are currently using in your function (too much overhead)?

Upvotes: 2

Views: 68

Answers (2)

Gareth Davis
Gareth Davis

Reputation: 28059

I think what you are refering to is using this in a jQuery call back function.

$('a').each(function(){
    this; // <-- is the DOMElement for a 'A' tag
});

You should use $(this) when you need to, i.e. when you need to run some form of jQuery method on the selected element.

Note you can retain a reference to the jQuery object for this to save recreating it alot:

// instead of
$('a').each(function(){
    $(this).thatPlugin();
    $(this).find("other").blat();        
    $(this).find("foo").blat();
    // 20 more 
});

// do:
$('a').each(function(){
    var $self = $(this); // keep a reference
    $self.thatPlugin();
    $self.find("other").blat();
    $self.find("foo").blat();
    // 20 more reusing $self
});

The naming of $self is purely personal preference.

Upvotes: 2

Pekka
Pekka

Reputation: 449475

It depends what you need. In the context of e.g. an event handler,

  • this is a reference to the native DOM object

  • $(this) is a reference to the jQuery extended object which adds all the jQuery goodness to an element (.css(), .attr() and the dozens, if not hundreds of additional methods).

In a jQuery extended object, the native DOM object is still available as the 0 property:

element = $("#element");
alert(element[0].id); // Outputs the native object's `id` property

If you need only the native functionality, there is no need to wrap it into a jQuery object, but you usually want to be able to access the extended functions at some point.

Re overhead, I don't have any hard data but I imagine this is one of the most heavily optimized operations in all of jQuery, as it often has to be applied to every element. Unless you're working with tens of thousands of elements, there is probably not going to be a notable difference either way.

Upvotes: 6

Related Questions