Quantcast
Viewing all articles
Browse latest Browse all 5

Using chaining properly

One of the coolest things about jQuery is it’s ability to chain method calls together. So, for example, if you want to switch the class on an element.

$('myDiv').removeClass('off').addClass('on');

If you’re anything like me then you probably learned that in your first 5 minutes of reading about jQuery but it goes further than that. Firstly, it still works across line breaks (because jQuery = JavaScript), which means you can write neat code like this…

$('#mypanel')
    .find('TABLE .firstCol')  
    .removeClass('.firstCol')  
    .css('background' : 'red')  
    .append('<span>This cell is now red</span>');

Making a habit of using chaining automatically helps you to cut down on your selector use too.

But it goes further than that. Let’s say that you want to perform several functions on an element but one of the first functions changes the element in some way, like this…

$('#myTable').find('.firstColumn').css('background','red');

We’ve selected a table, drilled down to find cells with a class of “firstColumn” and coloured them in red.

Let’s say we now want to colour all the cells with a class of “lastColumn” blue. Because we’ve used the find() funciton we’ve filtered out all the cells that don’t have a class of “firstColumn” so we need to use the selector again to get the table element and we can’t continue chaining, right? Luckily jQuery has an end() function which actually reverts back to the previous unaltered selection so you can carry on chaining, like this…

$('#myTable')
    .find('.firstColumn')
        .css('background','red')
    .end()
    .find('.lastColumn')
        .css('background','blue');

It’s also easier than you might think to write your own jQuery function which can chain. All you have to do is write a function which modifies an element and returns it.

$.fn.makeRed = function() {
    return $(this).css('background', 'red');
}

$('#myTable').find('.firstColumn').makeRed().append('hello');

How easy was that?


Viewing all articles
Browse latest Browse all 5

Trending Articles