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.
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").animate({width: "100%"}).animate({fontSize: "46px"}).animate({borderWidth: 30});
});
});
</script>
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:
<script>
$(document).ready(function(){
$("button").click(function(){
$("p")
.animate({width: "100%"})
.animate({fontSize: "46px"})
.animate({borderWidth: 30});
});
});
</script>
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.
<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>