Wednesday, August 12, 2009

jQuery Context

How many times have you wished there was an easier way to find DOM elements in a given HTML document? The jQuery javascript toolkit offers a powerful set of CSS selectors that enable developers to do just that; easily query DOM elements. The heart of the jQuery toolkit relies on these selectors. If you are using jQuery in your javascript applications to manipulate the DOM tree, you probably haven't noticed any performance issues while issuing queries. This is because jQuery is highly optimized.

However, the performance can still be improved. The jQuery() function is most often used to query the entire DOM tree. That is, if you issue a query for a DOM id, the selector is applied to every element in the document. More often than not, there is an opportunity to specify a context. For instance, when issuing a query, the developer may know that the given id exists somewhere within another element. Luckily, this element can be specified as a query context when issuing the query.

The benefit to using the context parameter is that the search for the specified DOM elements is narrowed. Possibly by a significant margin. There is another benefit to using the context parameter. Maintainability. Developers can easily deduce why a given query isn't yielding expected results for instance. Finally, the context can be used pragmatically to affect behavior. Below is an example of how to apply the context parameter to DOM queries using the core jQuery() function.
//Example; jQuery context.

var my_div=jQuery("#my_div");
var my_elements=jQuery(".my_elements", my_div);