Which is more efficient please?
var myElement = $(\"#the-name-of-my-element\")
myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSometh
It is always good practice to cache your nodes. The amount of work the JS engine has to do to locate the nodes is more expensive than the memory that you will use storing the node (of course unless you are storing a massive DOM tree or something).
So the winner is:
var myElement = $("#the-name-of-my-element")
myElement.doSomethingOnce;
myElement.doSomethingTwice;
...
myElement.doSomethingTenTimes;
Using $("#the-name-of-my-element")
everytime dom element search is performed.
Using var myElement = $("#the-name-of-my-element")
dom element search is performed only once and then stored to variable. So next time it will be accessed faster and without additional functions called.
So, in conclusion - assigning element to variable if you have to use it several times is more efficient than searching it every time.
with $("#the-name-of-my-element")
jQuery is traversing the entire dom tree to find all elements which apply to the selector rule.
Thus, putting the result in to a variable and using that instead of using the same selector a couple of times will be more efficient.
Caveats: if one of the called method (doSomeThing..()
) adds a new element with the same selector, this element won't be treated. As long as it's an ID, fine, but might be a problem when using classes (".someclass"
)
jQuery does not cache selectors - as detailed in this question:
Does jQuery do any kind of caching of "selectors"?
As a result, each time you perform $("#the-name-of-my-element")
jQuery is performing some work to match the selector.
For anything other than trivial code, I'd always cache selectors.
See also ...
At what level should I cache results of jQuery DOM queries?
If you are doing multiple tasks with same element than it's better to cache it to variable so JS will not re-select element on every call.
Also it's easier to maintain your code - e.g. if you want to change selector, than you have to change it in one place instead of going through code and searching for it.