Understanding jQuery statement chaining

This page discusses - Understanding jQuery statement chaining

Understanding jQuery statement chaining


Understanding jQuery statement chaining

JQuery provide statement chaining which can reduce the length of the code and reduce overhead of programmer.

In statement chaining , you can call multiple methods  in a single statement.

For example, you want to remove and assign a new css class to the div, you can do it like this :


Given below another example to select a column ,change it's color and append some text to it :


Chainable 'if' statement using jQuery 'iff' :

'iff' works like 'filter', it allows us to process the subset of filtered element as well as you can add or remove individual elements without braking chain.

For example ,given below code append  some value to 'div' if provided value is equal to 'bar' . If not , it will append another value to it :

function compare( x ) {
return a === 'set';
.append( '1' )
.iff( compare, 'select' )
.append( '2' )
.append( '3' );

Another example which are using two 'iff ' statements :

function my_callback( data ) {
.iff( data.success )
.append( '<img src="' + data.src + '"/>' )
.iff( data.error )
.append( 'An error has occurred.' )
.addClass( 'error' )
.appendTo( 'body' );

Chainable 'if-else' type statement in jQuery :

This code will first set the color of all links to blue, then append ??*?? to them. If k was set to anything else, the links would be colored red instead (and ??*?? would still be appended).

var k = 1;

k === 1, function(){
this.css({ color: 'purple' });
this.css({ color: 'red' });
.append( '*' );

Learn from experts! Attend jQuery Training classes.

Share on Google+Share on Google+

Understanding jQuery statement chaining

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Understanding jQuery statement chaining  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image