Optimizing with Chaining
In this page:
What is Chaining?
Chaining means calling one jQuery method right after another on the same line, which works because most jQuery methods return the same jQuery object they were called on rather than returning nothing. That returned object is what makes it possible to immediately call another method on it.
Example: What is Chaining?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="text">Text</p>
<script>
$("#text").css("color", "blue").fadeOut(1000);
</script>
</body>
</html>
Chain Common Methods
Many of jQuery's built-in methods — like .addClass(), .css(), and .fadeIn() — return the jQuery object itself after they finish, specifically so you can continue calling more methods right after them without needing a separate variable or statement for each step.
Example: Chain Common Methods
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="text">Text</p>
<script>
$("#text").addClass("highlight").css("padding", "10px").fadeIn();
</script>
</body>
</html>
Chaining Traversal Methods
DOM traversal methods like .parent(), .find(), and .siblings() can also be chained, which is especially useful when you need to select related elements — like finding a specific child, then styling it — all in one connected sequence of calls.
Example: Chaining Traversal Methods
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box"><p>Child</p></div>
<script>
$("#box").find("p").css("color", "red");
</script>
</body>
</html>
Chaining and Performance
Chaining can reduce how many times you re-select the same element, since each method in the chain operates on the result of the previous one rather than requiring a fresh selector call. It also tends to make a sequence of related operations easier to read as one coherent statement.
Example: Chaining and Performance
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="text">Text</p>
<script>
$("#text").css("color", "red").css("font-size", "20px").fadeIn();
</script>
</body>
</html>
Small Chaining Project
Chaining is best kept to sequences of genuinely related operations on the same element — for very long chains, breaking each method onto its own line keeps the code readable instead of producing one dense, hard-to-scan line.
Example: Small Chaining Project
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="text">Text</p>
<script>
$("#text")
.addClass("active")
.css("color", "green")
.fadeIn();
</script>
</body>
</html>
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: