How to use chaining in jQuery

Google+ Pinterest LinkedIn Tumblr +

If you are new to jQuery as well as JavaScript as such, some concepts might be new to you. One such thing is the idea of chaining.

You can think of chaining as a list of actions run one after another, but instead of launching them separately they relate to the previous actions result.

Let’s take this code for example:



Let us add an event to the header tag.

$(‘#outerContainer h2’).click(function(){
  // Perform some action

This means that when someone clicks on the header the function above will be called.

$(‘#outerContainer h2’).click(function(){
  var parentContainer = $(this).parent();

We start of by creating a jQuery object using this to set our context as the header (h2). This is followed by the jQuery function parent() that moves the context to the #outerContainer element. A reference to which ends up being assigned to the parentContainer variable.


$(‘#outerContainer h2’).click(function(){

The above would add a class ‘clicked’ to the #outerContainer and afterwards find all the children paragraphs which it then would hide. All this in one chain of actions.


As you can see by following the colours in the illustration the context of the actions in the chain can be affected by certain actions. You could split the actions into two types: ones that perform operations on an object (here: addClass(), or hide()) and ones that move your context to a different object (here: parent(), or children()).

To explain this even further, this is how the chain could be expanded:

$(‘#outerContainer h2’).click(function(){

However the above obviously means an unnecessary lookup as we locate the #outerContainer twice.

$(‘#outerContainer h2’).click(function(){
  var parentContainer = $(this).parent();

Now this is a lot better performance wise, however you can easily see how chaining can help group actions into logical groups and save space, as well as make your code a lot more readable.


About Author

Leave A Reply