I know that not all jQuery functions can be chained together. Is there a rule of thumb on this. When can we not chain 2 functions together.
4 Answers
You can chain when the function returns a "jQuery object".
For example, .css(property, value) can be chained, as the doc says it Returns jQuery:
while .height() cannot, because it returns an integer.
Typically, the functions that returns "jQuery objects" are those which typically would not "return a value", e.g. setter methods (.css(prop, val), .addClass()), event binders (.click(handler)), etc.
(Of course traverse methods (.parent(), .find(), etc.) can also be chained but the returned object will be different from the input.)
- 491,404
- 99
- 1,053
- 989
-
Can you give examples in JQuery where 2 functions cannot be chained. – Pinkie Mar 31 '11 at 20:05
-
@KennyTM, may I request you to have a look at a jquery question on a different topic here : http://stackoverflow.com/questions/13137404/jquery-find-div-class-name-at-a-certain-position-while-scrolling ? – Istiaque Ahmed Oct 31 '12 at 07:44
You can't chain a function that returns something other than a jQuery object. For example, attr() with one parameter to get the value of an attribute.
- 40,052
- 10
- 71
- 95
The way to distinguish is that functions which have side effects typically return jquery and can be chained where as functions with an actual return (like .text()) cannot.
- 18,796
- 15
- 68
- 95
if in the plugin they do:
return this; //<--jquery object
at the end then u can change it with other plugins :-)
- 142,114
- 39
- 237
- 299