Álvaro N. Franz
Álvaro N. Franz

Reputation: 1228

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.

Upvotes: 3

Views: 802

Answers (1)

Travis J
Travis J

Reputation: 82297

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.

Upvotes: 7

Related Questions