jQuery - jQuery chaining
jQuery chaining allows you to perform multiple actions on the same element(s) in a single statement, making your code shorter, cleaner, and more readable. Instead of writing multiple statements, you can link methods one after another because jQuery methods usually return the jQuery object itself.
1. Basic Syntax
$(selector).method1().method2().method3();
-
selector
→ Target element(s) -
method1, method2, ...
→ jQuery methods (like.css()
,.hide()
,.slideDown()
,.fadeIn()
, etc.) -
Each method acts on the same element(s).
2. Example: Without Chaining
$("#box").css("color", "white");
$("#box").css("background", "blue");
$("#box").slideUp(1000);
$("#box").slideDown(1000);
3. Example: With Chaining
$("#box").css("color", "white")
.css("background", "blue")
.slideUp(1000)
.slideDown(1000);
-
Cleaner and easier to read.
-
Executes sequentially on the same element.
4. Chaining with Callbacks
$("#box").slideUp(500)
.text("New Content")
.slideDown(500, function(){
$(this).css("color", "red");
});
Explanation:
-
Slide up the box.
-
Change text.
-
Slide down the box.
-
Change color after slide down completes (callback).
5. Combining Multiple Methods
You can chain CSS, effects, animations, and DOM manipulation methods:
$("#box").css("border", "2px solid black")
.fadeOut(500)
.fadeIn(500)
.slideUp(500)
.slideDown(500)
.html("<b>Updated Content</b>");
-
All actions happen in sequence.
-
Only requires one selector, not repeated multiple times.
6. Key Points About Chaining
-
Chaining works because most jQuery methods return the jQuery object itself.
-
Use chaining to reduce code redundancy.
-
You can mix different types of methods (CSS, animation, DOM manipulation).
-
Callback functions can also be included at the end of a chain for further actions.
7. Example: jQuery Chaining Demo
<!DOCTYPE html>
<html>
<head>
<title>jQuery Chaining Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
$("#btn").click(function(){
$("#box").css("color","white")
.css("background","green")
.slideUp(500)
.slideDown(500)
.fadeOut(500)
.fadeIn(500)
.text("Chaining Example!");
});
});
</script>
</head>
<body>
<button id="btn">Animate Box</button>
<div id="box" style="width:200px; height:100px; background:skyblue; margin-top:10px;">
Hello jQuery!
</div>
</body>
</html>
Explanation:
-
Clicking the button performs multiple actions sequentially on the box using a single chain.
Summary
-
jQuery chaining allows you to perform multiple operations on the same element without repeating the selector.
-
Works with CSS, effects, DOM manipulation, animations.
-
Can include callback functions at the end.
-
Makes code shorter, cleaner, and easier to maintain.