Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsIs there a reason why JQuery tends to use method chaining rather than nested methods?
For example JQuery tends to have methods all in a line using the dot, but other languages and frameworks have functions or methods nested inside each other. How would this affect the way we use chained methods rather than nested?
1 Answer
rydavim
18,814 PointsChaining lets you run multiple jQuery methods in a single statement. This means you can run several jQuery commands on the same element, one after the other. The primary benefit of this technique over using nesting is that the browser only needs to find the element once.
While the performance difference is negligible when running small programs, it can be important in larger ones.
Chaining can sometimes result in pretty long lines of code. Keep in mind that jQuery is pretty flexible when it comes to whitespace. You can often make chained methods easier to read by including line breaks after each method call.
// The following two bits of code are the same as far as jQuery is concerned.
$(".heading").css("color", "#424242").slideUp(1200).slideDown(1200);
$(".heading").css("color", "#424242")
.slideUp(1200)
.slideDown(1200);
Hopefully that helps to clarify why chaining is so common, and the options you have to make it more legible. Happy coding! :)