jQuery Chaining
Chaining is a jQuery technique that lets you run several methods on the same set of elements in a single statement. Because most jQuery methods return the jQuery object they were called on, you can attach the next method directly to the result, writing cleaner and often faster code.
What Is Chaining?
Normally you might select the same element several times to apply different actions. With chaining you select it once and let each method hand the element to the next, so the whole operation reads like a single sentence.
Without chaining
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">This is the box.</div>
<script>
$("#box").css("color", "red");
$("#box").slideUp(2000);
$("#box").slideDown(2000);
</script>
</body>
</html>With chaining
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">This is the box.</div>
<script>
$("#box").css("color", "red").slideUp(2000).slideDown(2000);
</script>
</body>
</html>Both versions do exactly the same thing, but the chained version selects #box only once. This saves the browser from searching the document repeatedly and keeps the intent clear.
Why Chaining Works
Most jQuery methods return the same jQuery object after they finish, a behaviour sometimes called 'returning this'. That returned object is exactly what the next method in the chain operates on, which is why you can keep adding methods one after another.
Formatting Long Chains
When a chain grows long, you can break it across multiple lines for readability. JavaScript ignores the extra whitespace, so the chain still runs as one statement. This style is common with animations that flow through several steps.
A readable multi-line chain
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:100px; height:100px; background-color:lightgray;"></div>
<script>
$("#box")
.css("background", "teal")
.animate({height: "200px"}, "slow")
.animate({width: "200px"}, "slow")
.fadeOut("slow");
</script>
</body>
</html>- Chaining runs multiple methods on the same selection in one line.
- The element is selected only once, which improves performance.
- It works because most action methods return the jQuery object.
- Getter methods usually stop a chain because they return a value, not the object.
- Long chains can be split across lines without breaking them.
Exercise: jQuery Chaining
What mechanism makes chaining like $("p").css("color","red").slideUp() work?