Reputation: 4734
regarding html elements that are being referenced frequently in code, such as a menu that is being shown/hidden often, what is the most lightweight jquery solution to re-access the element multiple times?
my current approach is to save the result in a variable (non global of course).
example:
$myElement = $('#my-element');
then use $myElement
rather than $('#my-element')
in all code that running withtin he scope of the variable.
another approach I am using is the $.data() method. I use this when I need to access one element based on another.
example:
$myElement.data('friend', $('my-element-friend'));
then use $myElement.data('friend')
instead of $('my-element-friend')
Are there other options to consider?
Are there cases where its best to simply repeat $('#my-element')
each time that I wish to access the element? (aside from when the reference is only used once in the entire runtime of the application)
Upvotes: 2
Views: 111
Reputation: 53929
Storing a reference in a variable (such as it is) is a good approach.
The only time I'd always use a selector is if the element in question is being destroyed/recreated all the time. Or if you are accessing a collection of elements that is changing between the calls (think $( '.SomeClass' )
).
Upvotes: 1