Understanding jQuery statement chaining

This page discusses - Understanding jQuery statement chaining

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 :

$('div1').removeClass('oldClass').addClass('newClass');

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

$('#Table1').find('.lastColumn').makeRed().append('changed');

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';
}; 
$('div')
.append( '1' )
.iff( compare, 'select' )
.append( '2' )
.end()
.append( '3' );

Another example which are using two 'iff ' statements :

function my_callback( data ) {
$('<div/>')
.iff( data.success )
.append( '<img src="' + data.src + '"/>' )
.end()
.iff( data.error )
.append( 'An error has occurred.' )
.addClass( 'error' )
.end()
.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;

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

Learn from experts! Attend jQuery Training classes.