jQuery chaining is a useful technique for connecting multiple methods calls in a single statement. This results in shorter and more readable code compared to applying the methods separately.
As you can see, the chaining version is much cleaner and concise. So how does this work under the hood?
The key things to know about chaining:
Each method call starts by selecting the element, in this case $('#elem')
The methods are chained together using periods
No need to store the return value in a variable, since each method works on the return value of the previous one
This is possible because jQuery methods return the original jQuery object. So $('#elem').css()
returns the $('#elem')
object, allowing us to call the next method .hide()
on it.
The end result is we can avoid reselecting the element over and over, making the code compact and readable.
Some common use cases where chaining helps:
Modifying style - chaining css()
, addClass()
, removeClass()
etc
Animations - chaining animate()
, fadeOut()
, slideUp()
one after another
DOM manipulation - chaining append()
, prepend()
, remove()
to build a structure
Chaining isn't always necessary, but it's a good technique to have in your toolbox for jQuery code.
Let me know in the comments if you have any other questions!
Top comments (0)