jQuery — Chaining
Basic Chaining
$("h1")
.css("color", "red")
.addClass("highlight")
.fadeIn(300);
Why Chain?
// Without chaining
$("h1").css("color", "red");
$("h1").addClass("highlight");
$("h1").fadeIn(300);
// With chaining
$("h1").css("color", "red").addClass("highlight").fadeIn(300);
Chain with Indentation
$("div")
.addClass("container")
.css("border", "1px solid #ccc")
.fadeIn(400)
.animate({ width: "300px" }, 500)
.queue(function() {
$(this).addClass("expanded");
$(this).dequeue();
});
Chaining with Find
$("ul")
.find("li")
.first()
.addClass("active")
.end()
.last()
.addClass("last-item");
end()
Reverts to the previous selection:
$("ul")
.find("li")
.addClass("item") // Applies to li elements
.end() // Back to ul
.addClass("has-items"); // Applies to ul
When NOT to Chain
- When methods return non-jQuery objects
- When readability suffers
- When using callbacks that need separate variables
Mini Practice
- Chain five different methods on a single element
- Use find() and end() together
- Replace sequential statements with a chain
- Queue a custom function in a chain
Up Next
Continue with HTML — getting and setting HTML content.
Related Topics
Frequently Asked Questions about Chaining
What is Chaining in jQuery?
Chaining is a fundamental concept in jQuery. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Chaining?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Chaining.
Why is Chaining important in jQuery?
Chaining is essential for jQuery development. Understanding this concept will help you write better code and solve real-world problems more effectively.