What is Chaining in jQuery?

You may have come across a term "Chaining" in jQuery. But do you know what is Chaining in jQuery? There is no specific definition available for this term in jQuery but it is also not different from the general meaning of Chain. In general term Chain is, "A connected flexible series of metal links used for fastening or securing objects and pulling or supporting loads." Below images dictates what is chaining.

Okay..As far as jQuery is concerned then undoubtedly Chaining is one of the most powerful feature of jQuery. Even in jQuery, Chaining means to connect multiple functions, events on selectors. To understand it better take a look at Sample Code 1 and 2.

Sample Code 1
    $('#dvContent').css('color', 'red');
Sample Code 2
          .css('color', 'red')
Both the sample codes above will perform the exact same thing but the only difference is that sample code 2 is using chaining. But code 2 is faster and shorter then code 1. But you must be thinking that why do I say so?

The problem with the sample code 1 is that for every statement, jQuery has to search the entire DOM and find the element and after that executes the attached function on it. But when chaining is used, then jQuery has to find the element only once and it will execute all the attached functions one by one. This is the advantage of Chaining.

Important points about Chaining

  • It makes your code short and easy to manage.
  • It gives better performance.
  • The chain starts from left to right. So left most will be called first and so on.

Not only functions or methods, chaining also works with events in jQuery. For example, below piece of code have click, mouseover and mouseout event for a button.
​$(document).ready(function() {
    $("#btnDummy").click(function(e) {
    }).mouseover(function(e) {
        alert("mouse over!")
    }).mouseout(function(e) {
        alert("mouse out!")
See result below.

See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..