jQuery Standards (8) – Chaining

Published on Author jameswiseman8 Comments


Use chaining as an alternative to variable caching and multiple selector calls.

Where chaining is used, appropriate line breaks and indentation should be used.

Do not over-chain. For long chains it acceptable to cache intermediate objects in a variable.


Chaining is one of the signature features of jQuery. Used correctly, it can reduce the amount of code we have to write and the amount of data that is held in memory.

Chaining can be considered as an alternative to:

  • Caching jQuery objects in local variables
  • Performing multiple selections

Where chaining is used, appropriate line breaks and indentation should be used.

When to Use Chains

Chains should not compromise the readability of the code. For long chains, finding and defining a formatting and indentation strategy can be troublesome.

It can be better in these instances to cache your jQuery object in a separate variable.

When a JavaScript object is cached in jQuery, the reference to the object is actually stored. This occupies a minimal amount of memory, leaving negligible performance degradation.

The items show some indentation strategies, and a representation with a cached variable:

Chain Formatting Examples

Long Chains – Indentation Strategy 1

            .text("Row " + String(AddCount)).end()
            .attr("id", "SomeId" + String(AddCount))
                .change(function() { ChangeFundRow() }).end()
            .attr("id", "SomeOtherId" + String(AddCount)).end()

Long Chains – Indentation Strategy 2

            .text("Row " + String(AddCount))
                .attr("id", "SomeId" + String(AddCount))
                .change(function() {
                .attr("id", "SomeOtherId" + String(AddCount))

To the untrained eye, either of the above may take some deciphering. In this case, a better strategy could be to cache your selections in a separate variable:

Long Chains – Caching Variable

var $clonedRow = objButton.parents("tr").clone();
          .text("Row " + nAddCount); 

    .attr("id", "FundManager" + nAddCount)
    .change( ChangeFundRow ); 

          .attr("id", "FundName" + nAddCount); 


jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining