Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>When Chaining Breaks</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> #box{width:200px;padding:15px;background:#eee;margin-bottom:10px;} </style> </head> <body> <button id="btn">Read Width, Then Style</button> <div id="box">Measure me</div> <div id="out" style="font-weight:bold;"></div> <script> $("#btn").on("click", function () { // .width() with no argument is a GETTER -- it returns a number, // not the jQuery object, so you can't chain another method on it. var boxWidth = $("#box").width(); // Continue chaining on the original selection instead: $("#box").addClass("active").css("border", "2px solid #04AA6D"); $("#out").text("Box width was: " + boxWidth + "px (chaining stopped there)"); }); </script> </body> </html>
Output