jQuery Method Chaining
$(selector) returns a jQuery object, and most jQuery methods that modify something (like .addClass(), .css(), .fadeIn()) also return that same jQuery object when they're done. That means you can call another method right after, on the same line, without re-selecting the element. This pattern is called method chaining, and it's one of the reasons jQuery code reads so smoothly.
1) Without Chaining vs. With Chaining
Without chaining, you repeat the selector every time. With chaining, you select once and call every method on the returned object.
// Without chaining -- selects '#box' three separate times
$('#box').addClass('active');
$('#box').css('color', 'white');
$('#box').fadeIn(400);
// With chaining -- selects '#box' once, then chains three methods
$('#box').addClass('active').css('color', 'white').fadeIn(400);
2) Multi-line Chaining Style
Long chains are easier to read split across lines, with each method indented on its own line starting with a dot.
$('#box')
.addClass('active')
.css('color', 'white')
.slideDown(300)
.delay(500)
.fadeOut(300);
3) When Chaining Breaks: Getter Methods
Not every method returns the jQuery object. Methods called with no argument to read a value — like .width(), .text(), or .val() — act as getters and return that value instead, ending the chain right there.
// .width() with no argument returns a number, NOT the jQuery object
var w = $('#box').width(); // w is now a number, e.g. 150
// Calling .addClass() on that number throws an error!
// $('#box').width().addClass('active'); // TypeError
// Fix: read the value separately, then chain on the original selection
var boxWidth = $('#box').width();
$('#box').addClass('active');
4) Returning Up the Chain with .end()
Traversal methods like .find() or .parent() change what's selected mid-chain. .end() steps back to the previous selection, so you can keep chaining without starting a new statement.
$('#list')
.find('li')
.addClass('item')
.end() // back to '#list'
.addClass('ready');
$.trim() return plain values, not a chainable jQuery object.