When I want to run a jQuery function on a single element that has the class .pizza, I do this:
$('.pizza').hide();
What is the difference between that and using first() or eq(0)?
$('.pizza').eq(0).hide();
My question comes because I want to cache the element into a variable to use it many times, and I don't know if it is a better practice to do:
var element_pizza=$('.pizza').eq(0);
Or just simply:
var element_pizza=$('.pizza');
Note: When I mean on a single element, I mean that there is only one element with the class pizza in the DOM.
Thanks for your time.
There is no difference when the set contains only one match.
Using .eq() would only be to select one specific match from a set. If the set has one element, then they will be equivalent.
In fact, it is a waste to use .eq(0) if the set contains one element because that will cause a new jQuery object to be created.
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