Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using eq(0) and not using it

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.

like image 797
Álvaro N. Franz Avatar asked Apr 16 '26 12:04

Álvaro N. Franz


1 Answers

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.

like image 71
Travis J Avatar answered Apr 19 '26 01:04

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!