1

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 ?

1
  • You make an unnecessary function call. It's not "harmful", just unnecessary. You wouldn't do $($('#clearBtn')) either, would you? Commented Aug 24, 2013 at 7:10

2 Answers 2

2

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'); 
Sign up to request clarification or add additional context in comments.

2 Comments

I have very little knowledge on how internal processes take place within the jQuery lib. Do you mean that it runs unnecessary functions and waste resources?
@crazyMAN: $ is a function. You run it unnecessarily by passing btn to it.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.