Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "return this.each()" do in jQuery?

Tags:

jquery

each

I'm looking at a jQuery plugin, which has a single function. After setting up the appropriate defaults though a constructor argument the function defines a couple of helper functions, and then as the last part returns a call to this.each(), like so:

return this.each(function() {
 //long method defined here
});

I understand the use of this.each() in modifying matching DOM elements and such, but what does the return statement accomplish? Some sort of array of modified DOM elements, which can then be chained in other calls?

I've read about this.each on this site but I can't quite figure what the return does here. Thanks for helping clear this up.

like image 967
larryq Avatar asked Sep 08 '11 16:09

larryq


4 Answers

.each returns the elements it was called on, so in this case, it is probably to maintain the ability of methods to be chained on that selector. That means that if the plugin'S method is called foo, you should be able to do

$("mySelector").foo().show();

Because foo returned the result of .each which is basically $("mySelector").

Hope that made sense.

like image 87
Alex Turpin Avatar answered Nov 11 '22 17:11

Alex Turpin


It allows for one to call a plugin or an event on a bunch of elements and then apply that same function or event to all of them

So if you do:

$('.selector').myPlugin();

And if, let us say, .selector contains 10 elements, all 10 elements would get whatever myPlugin does.


The reason for returning that .each statement is because .each() returns whatever it was given and it allows you to chain multiple functions and plugins together on one jQuery element.

For example:

$('.selector').myPlugin().yourPlugin();
like image 29
Naftali Avatar answered Nov 11 '22 19:11

Naftali


It makes functions chainable

http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability

like image 5
genesis Avatar answered Nov 11 '22 17:11

genesis


this make it possible to keep objects chain, so you can call jquery methods like this:

$("selector").css().mouseover().etc().blahblah();
like image 4
amiry jd Avatar answered Nov 11 '22 17:11

amiry jd