jQuery offers a powerful feature called method chaining, which enables you to perform multiple actions on the same set of elements in a single line of code.
This capability exists because most jQuery methods return a jQuery object that can be used to chain another method. Here's an example:
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").animate({width: "100%"}).animate({fontSize: "46px"}).animate({borderWidth: 30});
});
});
</script>
The example above demonstrates chaining three animate()
methods. When a user clicks the trigger button, it expands the <p>
element to 100% width. After the width change completes, the font-size
begins animating. Once that animation finishes, the border
animation starts.
Tip: Method chaining not only helps keep your jQuery code concise but also can improve your script's performance because the browser doesn't have to find the same elements multiple times to perform actions on them.
You can also break a single line of code into multiple lines for improved readability. For example, the sequence of methods in the above example could also be written as:
<script>
$(document).ready(function(){
$("button").click(function(){
$("p")
.animate({width: "100%"})
.animate({fontSize: "46px"})
.animate({borderWidth: 30});
});
});
</script>
Some jQuery methods do not return the jQuery object. Generally, setter methods, which assign a value to a selection, return a jQuery object, allowing you to continue chaining jQuery methods on your selection. On the other hand, getter methods return the requested value, so you cannot continue chaining jQuery methods on the value returned by the getter.
A typical example of this scenario is the html()
method. When called without parameters, it returns the HTML contents of the selected element instead of a jQuery object.
<script>
$(document).ready(function(){
$("button").click(function(){
// This will work
$("h1").html("Hello World!").addClass("test");
// This will NOT work
$("p").html().addClass("test");
});
});
</script>