Reputation: 10021
This is probably irrelevant for small and simple DOM elements, but assuming I have some large complicated DOM elements, is there a big performance difference between storing an element in a variable to use it vs constantly getting it with the jQuery selector?
$('myDomElement').css('height', 500);
$('myDomElement').css('width', 500);
// do more stuff using $('myDomElement')
vs
var myDomElement = $('myDomElement');
$(myDomElement).css('height', 500);
// do more stuff to myDomElement var
Upvotes: 1
Views: 136
Reputation:
It depends.
If all you are doing is a series of operations on one element, but then don't use that element afterwards, it is better to perform the lookup once and use jQuery chaining. Most jQuery functions return the element, so you can chain several functions together like so:
$('#myDomElement').css('height', 500)
.css('width', 500);
If you find yourself needing to perform lookups several times on the same elements, however, you should definitely save it to a variable. If you get to a point in your script where than element is no longer needed, don't forget to set it to null
or otherwise delete it. This will allow garbage collection to pick it up, and reduce the memory footprint of your script.
var el = $('#myDomElement');
el.css('height', 500);
//... further down in your script
el.css('height', 400);
el = null; //Will be picked up by GC
Hope that helps, good luck :)
Upvotes: 4
Reputation: 6770
The second approach is the right one because you are caching the selector for your element:
var myDomElement = $('myDomElement');
myDomElement.css('height', 500);
// do more stuff to myDomElement var
In this case jQuery will not parse your DOM again to find something it already has found before.
In the first case, every time you call $('myDomElement')
jQuery look for the element in DOM and it's totally unnecessary doing this search all the time to get the same element.
Upvotes: 1