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.
jQuery() Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.
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.
$ 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With