Chaining lets you perform multiple jQuery methods on the same set of elements in a single statement. It improves readability, reduces code repetition, and enhances performance by minimizing DOM lookups.
In jQuery, chaining works because most methods return the selected element(s). This allows you to apply multiple transformations or effects in a clean, readable chain.
// Basic jQuery chaining syntax
$("#element")
.css("color", "red")
.slideUp(500)
.slideDown(500);
// Simple chaining with effects
function simpleChain() {
$("#chainBox")
.css("color", "red")
.slideUp(1000)
.slideDown(1000);
}
// Complex chaining with animations
function complexChain() {
$("#chainBox")
.css({color: "blue", fontWeight: "bold"})
.fadeOut(500)
.fadeIn(500)
.animate({left: "100px", opacity: 0.7}, 1000)
.animate({left: "0px", opacity: 1}, 1000);
}
// Reset element to original state
function resetBox() {
$("#chainBox").css({color: "#000", fontWeight: "normal", left: "0", opacity: 1});
}
The buttons below demonstrate how chaining executes multiple operations smoothly on the same element without repeating the selector.
Select multiple methods to build your own chain and watch them execute in order!