cycling jQuery_Succinctly | Page 20

Hi , I ' m the DOM ! Script away !</ p > < script src =" http :// ajax . googleapis . com / ajax / libs / jquery / 1.7.2 / jquery . min . js "></ s cript >
< script > alert ( jQuery (' p '). text ()); </ script > </ body > </ html >
If I were to place the < script > before the < p > element , it would execute before the browser had loaded the < p > element . This would cause jQuery to assume the document does not contain any < p > elements . However , if I were to use the jQuery custom ready () event , then jQuery would not execute the code until the DOM was ready . But why do this , when we have control over the location of the < script > element in the document ? Placing jQuery code at the bottom of the page avoids having to using the ready () event . In fact , placing all JavaScript code at the bottom of a page is a proven performance strategy .
Grokking jQuery chaining
Once you have selected something using the jQuery function and created a wrapper set , you can actually chain jQuery methods to the DOM elements contained inside the set . Conceptually , jQuery methods continue the chain by always returning the jQuery wrapper set , which can then be used by the next jQuery method in the chain . Note : Most jQuery methods are chainable , but not all .
You should always attempt to reuse the wrapped set by leveraging chaining . In the code below , the text (), attr (), and addClass () methods are being chained .
Sample : sample6 . html
<! DOCTYPE html > < html lang =" en "> < body > < a ></ a > < script src =" http :// ajax . googleapis . com / ajax / libs / jquery / 1.7.2 / jquery . min . js "></ script > < script > ( function ($) { $(' a '). text (' jQuery ') // Sets text to jQuery , and then returns $(' a '). . attr (' href ', ' http :// www . jquery . com /') // Sets the href attribute and then returns
$(' a ').
. addClass (' jQuery '); // Sets class and then returns $(' a '). })( jQuery ) </ script > </ body > </ html >
20