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.
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.
Example : Without Chaining
Example : With Chaining
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.
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.
- It makes your code short and easy to manage.
- It gives better performance(faster).
- 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.
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 .