Formatting Your jQuery Chains - J Query

Problem
You have a lengthy jQuery chain that includes methods like .children() and .end() to operate on several related groups of elements. It’s getting hard to tell which operations apply to which elements:

Solution

Put each method call in the chain on its own line, and put the .operators at the beginning of each line. Then, indent each part of the chain to indicate where you are
switching to different sets of elements.
Increase the indentation when you use methods like .children() or .siblings() to select different elements, and decrease the indentation when you call .end() to return to the previous jQuery selection.
If you’re new to jQuery, you’ll probably want to read the recipes about basic chaining and.end() in Chapter (jQuery Basics):

Discussion
By breaking each call out onto its own line, it becomes very easy to scan the code and see what is happening. Using indentation to indicate when you’re modifying the set of elements makes it easy to keep track of when destructive operations are occurring and being undone via .end().
This style of indentation results in every call for any given set of elements always being lined up, even if they’re not consecutive. For example, it’s clear that the wrapper <div>has an element prepended and appended to it, even though there are operations on other elements in between.
Putting the .operators at the beginning of the lines instead of the end is just a finishing touch: it gives a better visual reminder that these are method calls and not ordinary function calls.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics