SpartanElite
SpartanElite

Reputation: 624

jQuery selector vs each

Lets say I have these two pieces of code - which are identical. Also lets assume that the '.selector' returns atleast 2 objects.

Snippet 1

$('.selector').myMethod();

Snippet 2

$('.selector').each(function(){
    $(this).myMethod();
});

Lets say for each one of the 'selected' returned objects I want to pass in the objects id wrapped up to myMethod().

So Snippet 2 could become

$('.selector').each(function(){
    $(this).myMethod({attribute: $(this).attr('id')});
});

How can I do something similar with Snippet 1 (i.e without using $.each())?
For obvious reasons this isn't correct

$('.selector').myMethod({attribute: $(this).attr('id')});

as $(this) does not represent any one of the 'selected' returned object.

EDIT: In Snippet 1 Is there any way to reference the returned object as jQuery itself 'loops' through each returned object and calls the method. (again w/o $.each()).

Upvotes: 1

Views: 140

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34426

The two pieces of code are not identical. One is a collection of objects and the other is a loop through a collection of objects. You can take an action on a collection that affect all equally or you can act individually on each object in the collection. Once you invoke the each() function you are individualizing objects in the collection.

To answer your question, there is no way to reference the returned collection of objects as if you were looping and applying a different function, calculation or result to each individual item in the collection.

Upvotes: 1

Related Questions