jQuery Method Chaining and Callbacks
Most jQuery methods return the jQuery object they were called on. This lets you add the next method right after, in a long “chain”. You find the elements only one time, so the code is shorter and faster.
Without and with chaining
<p id="msg">Hello</p>
// without chaining: find the element three times
$('#msg').css('color', 'red');
$('#msg').text('Welcome');
$('#msg').addClass('big');
<p id="msg" style="color: red;" class="big">Welcome</p>
// with chaining: find the element one time
$('#msg').css('color', 'red').text('Welcome').addClass('big');
<p id="msg" style="color: red;" class="big">Welcome</p>
Line breaks make it readable
$('#msg')
.css('color', 'blue')
.text('Hello again')
.addClass('highlight')
.attr('title', 'A message');
<p id="msg" style="color: blue;" class="highlight" title="A message">Hello again</p>
Which methods can be chained?
The methods which set something return the jQuery object, so you can chain them. The methods which get a value (like .text() without an argument) return the value, so they are at the end of the chain.
var result = $('#msg').text('Hi').text();
console.log(result);
console.log(typeof $('#msg').text());
Hi
string
Callbacks
Effects and animations take time. Your next line of code does not wait for them. If you want to do something after the effect ends, use a callback function.
<div id="box">Box</div>
$('#box').hide(200);
console.log('1. this line runs right after the effect is started');
$('#box').show(200, function () {
console.log('2. callback: the effect is complete');
});
1. this line runs right after the effect is started
2. callback: the effect is complete
Chain effects in a queue
The effects of one element are put in a queue, so they run in order, even without callbacks.
$('#box').slideUp(300).delay(500).fadeIn(300);
end() to go back
When you use find(), children() or filter() in the chain, the selection changes. The method .end() goes back to the previous selection.
<ul id="list">
<li class="a">One</li>
<li class="b">Two</li>
</ul>
$('#list')
.find('.a').css('color', 'red')
.end()
.find('.b').css('color', 'blue');
<ul id="list">
<li class="a" style="color: red;">One</li>
<li class="b" style="color: blue;">Two</li>
</ul>
Common mistake
If a method in the chain returns no jQuery object (for example .text() used as a getter, or .length), the next method fails with an error like “is not a function”.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |