jQuery Chaining
In this tutorial you will learn how chain multiple methods in jQuery.
jQuery Method Chaining
The jQuery provides another robust feature called method chaining that allows us to perform multiple action on the same set of elements, all within a single line of code.
This is possible because most of the jQuery methods return a jQuery object that can be further used to call another method. Here's an example.
Example
Try this code »<script>
$(document).ready(function(){
$("button").click(function(){
$("p").animate({width: "100%"}).animate({fontSize: "46px"}).animate({borderWidth: 30});
});
});
</script>
The above example demonstrate the chaining of three animate()
method. When a user click the trigger button, it expands the <p>
to 100% width. Once the width
change is complete the font-size
is start animating and after its completion, the border
animation will begin.
Tip: The method chaining not only helps you to keep your jQuery code concise, but it also can improve your script's performance since browser doesn't have to find the same elements multiple times to do something with them.
You can also break a single line of code into multiple lines for greater readability. For example, the sequence of methods in the above example could also be written as:
Example
Try this code »<script>
$(document).ready(function(){
$("button").click(function(){
$("p")
.animate({width: "100%"})
.animate({fontSize: "46px"})
.animate({borderWidth: 30});
});
});
</script>
Some jQuery methods doesn't return the jQuery object. In general, setters i.e. methods that assign some value on a selection return a jQuery object, that allows you to continue calling jQuery methods on your selection. Whereas, getters return the requested value, so you can't continue to call jQuery methods on the value returned by the getter.
A typical example of this scenario is the html()
method. If no parameters are passed to it, the HTML contents of the selected element is returned instead of a jQuery object.
Example
Try this code »<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>