I am using this jQuery selector multiple times in my JSP:
$("#customers tbody tr td input[type='checkbox'][name='selectedCustomers']")
The solution I found on some blogs is that I should do first:
var customer=$('#customers')
And then use the above customer object for further calls.
customer.find("tbody tr td input[type='checkbox'][name='selectedCustomers']")
My question is, does this solution will make any difference and why?
My understanding
When I do
$("#customers tbody tr td input[type='checkbox'][name='selectedCustomers']")
jQuery internally will first get the object associated with div id="customers"
(by document.getElementById("customers")) and then will traverse to the specified
checkbox
. And if I go by the suggested solution then document.getElementById("customers")
will be fired only once and the rest will be the same. So I am saving myself from unnecessary multiple document.getElementById
but the rest will be the same. Is my understanding correct? If yes is, just for the sake of my knowledge, is document.getElementById
a more costly operation?
EDIT:-
i am not using only above said selector multiple times but also other possible selector under div id="customer". So question again is whats is difference in terms of performance if I cache the customer object first and if i don't do it?
There is no way you need to be that specific. I'm guessing, at the very most, this:
$('#customers td [name="selectedCustomers"]')
... which should improve performance. Next, if you're actually querying for selectedCustomers
each time, you should cache the whole thing:
var selectedCustomers = $('#customers td [name="selectedCustomers"]');
Otherwise, if the name is dynamic, and you only have one item with the same name per page...
var item = $(document.getElementsByName(someName)[0]);
Caching just $('#customers')
, on the other hand, is pretty much pointless. .find
on customers
will do just as much work as the whole selector in the first place, especially with querySelector
support.
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