18

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.

Jeremy
  • 1
  • 85
  • 340
  • 366
Pinkie
  • 10,126
  • 22
  • 78
  • 124

4 Answers4

27

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: enter image description here

while .height() cannot, because it returns an integer.

enter image description here

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.)

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 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
4

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.

Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
3

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.

T. Stone
  • 19,209
  • 15
  • 69
  • 97
2

if in the plugin they do:

return this; //<--jquery object

at the end then u can change it with other plugins :-)

Naftali
  • 144,921
  • 39
  • 244
  • 303