skip to content

Understanding with Special Events

2 min read

When selecting elements jQuery has an optional second argument called context. This context provides a means to limit the search within a specific node. This is great when you have a very large DOM tree and need to find, for example, all the <a> tags within a specific part of the DOM tree. I’ve seen various articles, usually performance related, stating that you should be using a context for your selectors. While it is true that using a context for your selectors can potentially boost performance, most of these articles misuse the context.

Finding the Context

As of jQuery 1.3 the context is exposed as a property on the jQuery collection. Here is how you can check to see what the context is.

$('a').context; // => document

Running the above code shows that the context is the document element. In fact, the default context for all jQuery collections is the document in which jQuery was loaded. In other words, selectors are run against the whole document by default.

Changing the Context

The context needs to be a node to work properly. This is the part that is often overlooked. I’ve overlooked it in the past as well. Lots of examples out there tell you to just pass a second selector to jQuery to act as the reference node for the search. While this seems to work, it is still running the search on the whole document.

Here is an example of passing a second selector as the context. By looking at the context property you can see that the context is still the document though.

$('a', '#myContainer').context; // => document

When jQuery encounters another selector for the context it actually converts it to say the following instead.

$('#myContainer').find('a');

This conversion also happens the same way if you pass a jQuery collection as the context.

Now lets actually look at how we can change the context for the jQuery collection.

// get the node for the context
var context = $('#myContainer')[0];

// pass the context as the second argument
$('a', context).context; // => <div id="myContainer">

From this example we can see that passing a node as the second argument actually changes the context for the jQuery collection.

jQuery 1.3.3 and .live()

In jQuery 1.3.x, the .live() method binds its event handlers to the document. In the upcoming jQuery 1.3.3 release the .live() method will bind its events to the context of the jQuery collection. This means your .live() events can be more focused and potentially faster.