jQuery Kochbuch

Page 72

Solution As well as passing a selector expression to jQuery() or $(), you can pass a second argument that specifies the context. The context is where jQuery will search for the elements matched by your selector expression. The context parameter is probably one of the most underused of jQuery’s features. The way to use it is incredibly simple: pass a selector expression, a jQuery object, a DOM collection, or a DOM node to the context argument, and jQuery will search only for elements within that context. Here’s an example: you want to select all input fields within a form before it’s submitted: jQuery('form').bind('submit', function(){ var allInputs = jQuery('input', this); // Now you would do something with 'allInputs' });

Notice that this was passed as the second argument; within the handler just shown, this refers to the form element. Since it’s set as the context, jQuery will only return input elements within that form. If we didn’t include that second argument, then all of the document’s input elements would be selected—not what we want. As mentioned, you can also pass a regular selector as the context: jQuery('p', '#content');

The preceding code returns exactly the same collection as the following selector: jQuery('#content p');

Specifying a context can aid in readability and speed. It’s a useful feature to know about!

Discussion The default context used by jQuery is document, i.e., the topmost item in the DOM hierarchy. Only specify a context if it’s different from this default. Using a context can be expressed in the following way: jQuery( context ).find( selector );

In fact, this is exactly what jQuery does behind the scenes. Considering this, if you already have a reference to the context, then you should pass that instead of a selector—there’s no point in making jQuery go through the selection process again.

2.11 Using the Context Parameter | 49


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.