Pinkie
Pinkie

Reputation: 10256

jQuery chaining: Can everything be chained? When can we not chain?

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.

Upvotes: 18

Views: 3643

Answers (4)

kennytm
kennytm

Reputation: 523344

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

Upvotes: 27

T. Stone
T. Stone

Reputation: 19495

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.

Upvotes: 3

Mike DeSimone
Mike DeSimone

Reputation: 42805

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.

Upvotes: 4

Naftali
Naftali

Reputation: 146310

if in the plugin they do:

return this; //<--jquery object

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

Upvotes: 2

Related Questions