You plan to use a local variable to cache a potentially slow search value.
How slow is the challenge itself? If fast, caching will not make much difference. If it is slow, then the cache on the first call. Selectors vary widely in cost - just think about how the code should clean the element. If this is an identifier, then the browser provides quick access, while classes and nodes require a full DOM scan. Check out jQuery (Sizzle) selector profiling to understand them.
Can you connect the challenges? . Use the chaining method whenever possible. This ensures efficiency without introducing another variable.
In your example, I would write:
$('#elemId').addClass('someClass').set('some attribute', 'some value');
How is the code read? Usually, if the same method is called several times, it is more understandable by DRY and uses a local variable. Then the reader understands the intention better - you do not force them to scan all jQuery calls to make sure they are the same. BTW, a pretty standard convention is the name of jQuery variables starting with $ - which is legal in Javascript - as in
var $elem = $('#elem'); $elem.addClass('someClass');
Hope this helps.
source share