Lately i have been wondering if there is a performance difference between repeating the selector just over and over again or just using a var and store the selector in that and just refer to it.
$('#Element').dothis();
$('#Element').dothat();
$('#Element').find('a').dothat();
or just
var Object = $('#Element');
Object.dothis();
Object.dothat();
$('a', Object).dothat();
I prefer the second way because it looks cleaner and is better maintainable.
ID and Element selector are the fastest selectors in jQuery.
Ofceauce ID is a faster selector in both CSS and JavaScript.
Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.
There is certainly a performance difference, since sizzle does not have to be executed each time, however, there is also a functionality difference. If the dom happens to change between the 1st and 3rd calls, the cached jQuery object will still contain the old set of elements. This can often occur if you cache a set and then use it in a callback.
I prefer the second way. It will be easier to maintain code even if an element id or class changes.
There is another fast way. It is as fast as your second code.
$('#Element')
.dothis()
.dothat()
.find('a')
.dothat();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With