Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Without vs. With Chaining</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> #box{width:200px;padding:15px;background:#eee;display:none;margin-bottom:10px;} #box.active{border:2px solid #04AA6D;} </style> </head> <body> <button id="withoutBtn">Run Without Chaining</button> <button id="withBtn">Run With Chaining</button> <div id="box">I'm the box!</div> <script> function reset() { $("#box").removeClass("active").css({ color: "", display: "none" }).show(); $("#box").hide(); } $("#withoutBtn").on("click", function () { reset(); // Without chaining -- selects '#box' three separate times $("#box").addClass("active"); $("#box").css("color", "green"); $("#box").fadeIn(400); }); $("#withBtn").on("click", function () { reset(); // With chaining -- selects '#box' once, then chains three methods $("#box").addClass("active").css("color", "blue").fadeIn(400); }); </script> </body> </html>
Output