jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
them.” In our code example, we found all the elements in the HTML page using<br />
the <strong>jQuery</strong> function (<strong>jQuery</strong>()), and then using <strong>jQuery</strong> methods we did something with<br />
them (e.g., hide(), text(), addClass(), show()).<br />
Chaining<br />
<strong>jQuery</strong> is constructed in a manner that will allow <strong>jQuery</strong> methods to be chained. For<br />
example, why not find an element once and then chain operations onto that element?<br />
Our former code example demonstrating the “Find some elements and do something<br />
with them” concept could be rewritten to a single JavaScript statement using chaining.<br />
This code, using chaining, can be changed from this:<br />
to this:<br />
//hide all divs on the page<br />
<strong>jQuery</strong>('div').hide();<br />
//update the text contained inside of the div<br />
<strong>jQuery</strong>('div').text('new content');<br />
//add a class attribute with a value of updatedContent to all divs<br />
<strong>jQuery</strong>('div').addClass("updatedContent");<br />
//show all divs on the page<br />
<strong>jQuery</strong>('div').show();<br />
<strong>jQuery</strong>('div').hide().text('new content').addClass("updatedContent").show();<br />
or, with indenting and line breaks, to this:<br />
<strong>jQuery</strong>('div')<br />
.hide()<br />
.text('new content')<br />
.addClass("updatedContent")<br />
.show();<br />
Plainly speaking, chaining simply allows you to apply an endless chain of <strong>jQuery</strong> methods<br />
on the elements that are currently selected (currently wrapped with <strong>jQuery</strong> functionality)<br />
using the <strong>jQuery</strong> function. Behind the scenes, the elements previously selected<br />
before a <strong>jQuery</strong> method was applied are always returned so that the chain can continue.<br />
As you will see in future recipes, plugins are also constructed in this manner (returning<br />
wrapped elements) so that using a plugin does not break the chain.<br />
If it’s not immediately obvious, and based on the code in question, chaining also cuts<br />
down on processing overhead by selecting a set of DOM elements only once, to then<br />
be operated on numerous times by <strong>jQuery</strong> methods by way of chaining. Avoiding unnecessary<br />
DOM traversing is a critical part of page performance enhancements. Whenever<br />
possible, reuse or cache a set of selected DOM elements.<br />
1.0 Introduction | 5