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');
}
It doesn’t query the DOM in this instance.
$()wraps thethis(or whatever else you have inside it) with a jQuery wrapper object.By caching it:
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');