English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
jQuery provides another powerful feature called method chaining.
Chaining allows us to run multiple jQuery methods on the same element in a single statement.
So far, we have written one jQuery statement at a time (one after another).
However, there is a technique called chaining, which can run multiple jQuery commands on the same element in a single statement.
In this way, the browser does not need to search for the same element multiple times.
This is possible because most jQuery methods return a jQuery object, which can be further used to call another method.
The following examples are chained togethercss(),hide()andshow()Method:
$("button").click(function(){ $("p").css("background-color", "coral").hide(2000).show(2000); });Test to see‹/›
We can also split a single line of code into multiple lines to improve readability.
For example, the method sequence in the above example can also be written as:
$("button").click(function(){ $("p") .css("background-color", "coral") .hide(2000) .show(2000); });Test to see‹/›
We can chain any number of methods in a single statement:
$("button").click(function(){ $("div") .animate({width:"500px"}) .animate({height:"200px"}) .animate({fontSize: "10em}) .animate({opacity: 0.3}); });Test to see‹/›
Note:Some jQuery methods do not return a jQuery object, while others return it based on the parameters we pass to it. Consider the following example:
// Correct Usage $("p").css("background-color", "coral").hide(2000).show(2000); // Incorrect Usage $("p").css("background-color", "coral").hide().show();