Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return this.each(function()) in jQuery plugins?

Some of the tutorials and examples I have seen for developing jQuery plugins tend to return

this.each(function () {     //Plugin code here }); 

at the end of the function that instantiates the plugin but I have yet to see any reasoning behind it, it just seems to be a standard that everyone follows. Can anyone enlighten me as to the reasoning behind this practice?

Edit: For clarification my question was not about why to return this, but rather why the plugin should return this.each.

like image 704
Corey Sunwold Avatar asked Apr 20 '10 19:04

Corey Sunwold


People also ask

What does the jQuery function return?

jQuery() Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.

Is jQuery return value?

Like the others said, jQuery returns jQuery objects in most cases, and accessing the actual object can be accomplished using an indexer [] or the get method.

What is $$ in jQuery?

$ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it.

What is $() Javascript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.


1 Answers

When you filter elements with a selector ($('.myclass')), it can match more than only one element.
With each, you iterate over all matched elements and your code is applied to all of them.

like image 85
Felix Kling Avatar answered Sep 20 '22 04:09

Felix Kling