Method Chaining
Call several jQuery methods in a row on the same selection.
Syntax
$(selector).methodA().methodB().methodC();Most jQuery methods return the same jQuery object, so you can chain calls one after another. This runs them in order on the same elements.
$("#box")
.css("color", "white")
.slideUp(300)
.slideDown(300);Chaining keeps code compact and avoids re-selecting the same elements repeatedly.
Example
Loading editor…
Press Run to see the result.
When to use it
- A modal open sequence chains .css(), .show(), and .addClass() to set styles and reveal the dialog in one statement.
- A button click chain calls .text(), .prop('disabled', true), and .addClass() to update the label and disable it atomically.
- A slide-and-fade combination chains .slideUp() and .fadeOut() to create a compound closing animation.
More examples
Chain css and text in one line
Each method in the chain returns the same jQuery object, so the next method acts on the same element.
<p id="msg">Click the button</p>
<button id="go">Go</button>
<script>
$(function () {
$("#go").click(function () {
$("#msg")
.css("color", "white")
.css("background", "#3498db")
.text("Done!");
});
});
</script>Chain animation and class change
.delay() pauses the queue between animations; every chained call queues after the previous one finishes.
<div id="panel" style="padding:20px;background:#eee;">Panel</div>
<button id="close">Close</button>
<script>
$(function () {
$("#close").click(function () {
$("#panel")
.addClass("closing")
.fadeOut(400)
.delay(100)
.slideUp(300);
});
});
</script>Chain filter and manipulation
.filter() narrows the matched set mid-chain; subsequent methods only act on the filtered subset.
<ul id="items">
<li class="active">Alpha</li>
<li>Beta</li>
<li class="active">Gamma</li>
</ul>
<script>
$(function () {
$("#items li")
.filter(".active")
.css("font-weight", "bold")
.prepend("★ ");
});
</script>
Discussion