cycling jQuery_Succinctly | Page 27

( jQuery );
</ script > </ body > </ html >
Notes : Using get () will end jQuery ' s chaining . It will take the wrapper set and change it into a simple array of DOM elements that are no longer wrapped with jQuery functionality . Therefore , using the . end () method cannot restore chaining after . get ().
Checking to see if the wrapper set is empty
Before you begin to operate on a wrapper set , it is logical to check that you have , in fact , selected something . The simplest solution is to use an if statement to check if the wrapper set contains any DOM elements .
Sample : sample14 . html
<! DOCTYPE html > < html lang =" en "> < body > < a > jQuery </ a > < script src =" http :// ajax . googleapis . com / ajax / libs / jquery / 1.7.2 / jquery . min . js "></ script > < script > if ( jQuery (' a '). get ( 0 )) { // Is there an element in the set ? jQuery (' a '). attr (' href ', ' http :// www . jquery . com ');
} if ( jQuery (' a '). length ) { // Check the length of the set . Can also use . size () jQuery (' a '). attr (' title ', ' jQuery ');
} </ script >
</ body > </ html >
The truth of the matter is the above if statements are not totally necessary , because jQuery will fail silently if no elements are found . However , each method chained to any empty wrapper set still gets invoked . So while we could actually forgo the use of the if statements , it is likely a good rule of thumb to use them . Invoking methods on an empty wrapper set could potentially cause unnecessary processing , as well as undesirable results if methods return values other than the wrapper set , and those values are acted upon .
27