Reputation: 714
I just read that if you are referring to the same DOM element over and over in a function it is better to cache them in a local variable like :
var btn = $('#clearBtn');
I have followed this where necessary but when accessing back this object I have always used $(btn).somemethod();
although we can access this directly like btn.somemethod();
I just need to know whether this will have a negative impact ?
Upvotes: 1
Views: 1071
Reputation: 3640
btn.somemethod();
will work, and is the correct way, since btn
is already a jQuery object.
Besides, unless you call $('#clearBtn');
a lot of times in a short period of time, I wouldn't bother caching it.
Upvotes: 0
Reputation: 298106
There's no point in passing the jQuery object through the jQuery constructor. It's just wasteful. If the dollar sign looks nice to you, just prepend it to the variable name and use $btn
in place of $(btn)
:
var $btn = $('#clearBtn');
Upvotes: 2