Episode 8 of 24
Chaining in jQuery
Learn how to chain multiple jQuery methods together for cleaner, more efficient code.
Chaining is one of jQuery's most elegant features. It lets you run multiple methods on the same selection in a single statement.
How Chaining Works
Most jQuery methods return the jQuery object itself, so you can call another method right after:
// Without chaining — repetitive
$("#title").css("color", "red");
$("#title").fadeOut();
$("#title").fadeIn();
$("#title").text("New Title");
// With chaining — clean and efficient
$("#title")
.css("color", "red")
.fadeOut()
.fadeIn()
.text("New Title");
Why Chain?
- Fewer DOM lookups — jQuery only finds the element once
- Cleaner code — more readable and concise
- Better performance — reduces overhead
Complex Chains
$("ul li")
.filter(":even")
.css("background", "#f0f0f0")
.end() // Go back to all li
.filter(":odd")
.css("background", "#e0e0e0")
.end() // Go back to all li again
.first()
.css("font-weight", "bold");
The .end() Method
.end() reverts to the previous selection in the chain:
$("ul")
.find("li") // Now working with li
.css("padding", "10px")
.end() // Back to ul
.css("border", "1px solid #ddd");
Practical Example
// Build a styled notification
$("<div>")
.addClass("notification")
.text("Item saved successfully!")
.css({
padding: "1rem",
background: "#d4edda",
borderRadius: "8px",
marginTop: "1rem"
})
.hide()
.appendTo(".container")
.fadeIn(400);