Using Method Chaining in jQuery

When you use method chaining in jQuery, it ensures that you never have to use the same selector more than once. Over-using a selector can seriously slow down your code, as every time you call on a selector you're forcing the browser to go looking for it. By combining or "chaining" multiple methods, you can seriously cut down on the amount of times you make your browser look for the same elements without having to set any variables.

Here's an example of what your jQuery could look like before you employ method chaining:

$("#header").css('color', '#333");
 $("#header").addClass("bigger");
 $("#header").toggle();

To chain all of these methods so you only have to use the $("#header") selector once, you simply need to connect them using a period ".":

$("#header").css('color', '#333").addClass("bigger").toggle();

Now, when whatever your event will be to trigger this code occurs, the header will change color, add the .bigger class and whatever CSS properties come along with it, and it will toggle from view -- all while the browser only has to find the selector once, rather than three times. Method chaining is a great way to clean up your code, keep things concise, and make sure your code is running as quickly as it possibly can.