Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does $(this) query the dom?

Tags:

jquery

dom

this

I was wondering if passing this to the jQuery function actually causes it to search in the DOM for it. The question has a specific context.

Let's say I have:

$('#foo').click(function(){
  var id = $(this).attr('id');
  var someVal = $(this).data('someVal');
}

Will jQuery query the DOM to provide its functions or are all the information read and taken from the JavaScript object this?

And is there a performance difference to:

$('#foo').click(function(){
  var elem = $(this);
  var id = elem.attr('id');
  var someVal = elem.data('someVal');
}
like image 873
Marvin Strenger Avatar asked Nov 15 '12 22:11

Marvin Strenger


2 Answers

It doesn't query the DOM in this instance. $() wraps the this (or whatever else you have inside it) with a jQuery wrapper object.

By caching it:

var $this = $(this);
 // you will see code have a $ before or after a variable ( $this, this$, etc )
 // signifying it is a jQuery wrapped object

You have the performance saving of only wrapping it with jQuery once. As opposed to having it go inside jQuery and wrap it over and over again. It is good coding practice to cache it.

note: Of course if you have $('#whatever') it will be querying the DOM, since you have provided a selector for it to retrieve, then it wraps it with jQuery. So if you'll be reusing it over and over it makes sense to save it as well! var $whatever = $('#whatever');

like image 121
Mark Pieszak - Trilon.io Avatar answered Nov 05 '22 13:11

Mark Pieszak - Trilon.io


If you have an DOM element in this, then $(this) does not query the DOM. It just puts a jQuery wrapper object around that one DOM element.

This is not an expensive operation, but you want to avoid doing it unnecessarily. for instance, you sometimes see this sort of code:

$("some_selector_here").mousemove(function() {
   if ($(this).hasClass('foo')) {
       $(this).doSomething();
   }
   else {
       $(this).doSomethingElse();
   }
});

There's just no reason for that. Instead:

$("some_selector_here").mousemove(function() {
   var $this = $(this);
   if ($this.hasClass('foo')) {
       $this.doSomething();
   }
   else {
       $this.doSomethingElse();
   }
});

It almost certainly doesn't matter in, say, a click handler, although I would still say it's poor form. But in things that get called a lot, like mousemove, well, avoid unnecessary function calls and memory allocation. :-)

like image 8
T.J. Crowder Avatar answered Nov 05 '22 13:11

T.J. Crowder