Using Method Chaining in jQuery

The jQuery Method chaining allows you to perform multiple action on the same set of elements, all within a single line of code. This allows you to do command chaining , where you can perform multiple methods on the same set of elements, which is really neat because it saves you and the browser from having to find the same elements more than once.

How Method Chaining Works?

Almost all jQuery methods return a jQuery object. I.e., after you've run a method on your selection, you can continue running more methods. You can even change your selection, and continue to run methods on your new selection.
$('myDiv').removeClass('off').addClass('on');
Each jQuery function returns an instance of the jQuery class, which can then have methods called on it. You could break it down, and this code would have the same effect.
jQuery_obj = $('myDiv'); jQuery_obj = jQuery_obj.removeClass('off'); jQuery_obj = jQuery_obj.addClass('on');
Example : Without Chaining
$(document).ready(function(){ $('#myContent').addClass('hello'); $('#myContent').css('color', 'red'); $('#myContent').fadeOut('fast'); });?
Example : With Chaining
$('#myContent').addClass('hello').css('color', 'red').fadeOut('fast');
When chaining , the line of code could become quite long. However, jQuery is not very strict on the syntax; you can format it like you want, including line breaks and indentations.
$(document).ready(function(){ $('#myContent').addClass('hello') .css('color', 'red') .fadeOut('fast'); });?
Above examples do the same thing and it is faster and shorter in code. Without Chaining , JQuery has to search the entire DOM to find the element and after that it executes the function on it.

Advantages:

  1. It makes your code short and easy to manage.
  2. It gives better performance(faster).
  3. 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() { $("#myBtn").click(function(e) { alert("Button Clicked !"); }).mouseover(function(e) { alert("mouse over!") }).mouseout(function(e) { alert("mouse out!") }); });
It is important to note that some methods doesn't return the jQuery object , while others only return it depending on the parameters you pass to it. If no parameters are passed to it, the current text of the selected element(s) is returned instead of a jQuery object, while a single parameter causes jQuery to set the specified text and return a jQuery object . example
$(document).ready(function(){ $("button").click(function(){ // This will work $("h1").html("Chaining Here...!").addClass("Hi"); // This will NOT work $("p").html().addClass("Hi"); }); });