Context matters (Should know)
So far I've mentioned vaguely something called context that can be used during a selection. This recipe illustrates how and why we use the second parameter of jQuery, context.
How to do it...
Our goal is to apply a border to all of the <li>
descendants of an element having ID content, using the context parameter. Perform the following steps:
Create a copy of the
child-filters.html
file and rename it ascontext-matters.html
.Edit the
<head>
section of the page adding this code:<script> $(document).ready(function() { $('li', '#content').css('border', '2px solid #000000'); }); </script>
Save the file and open it with your favorite browser.
How it works...
This recipe is very simple because I want you to focus on the consequences of using the second parameter of the constructor. In the only statement inside the anonymous function, we've passed two arguments to the constructor. The first is the usual selector, while the second, context
, can be a DOM element, the document, or a jQuery object and acts as an ancestor. So, in our example, we retrieved the <li>
elements descendants of the element having id content
and then applied a solid black border with 2px width.
There's more...
We've already seen how we can combine multiple selectors to create a more complex one. To achieve the goal of this recipe using your current knowledge, you should have thought of a selector like the following:
$('#context li')
If you did, give me five! This selector would do the job, but there's a more efficient way. Before talking about performance, let's discover a little more.
What exactly is context
? By default, jQuery performs searches within the DOM starting from the document root. The framework splits the selector into multiple parts and then processes them, but this process is usually slower than the one using context
. The latter is used to restrict the searches to one or more subtrees, depending on the selector used, that usually will result in a performance improvement.
When you use the second argument, what jQuery does is to firstly retrieve elements based on the context
selector and then collects the descendants that match the first parameter, selector
. The second argument helps a lot in case where you have a very large DOM and the selector you're using really narrow down the subtree(s) where it'll perform the second phase of the search.
The most observant of you may guess why I talked about ancestor and not parent. The answer is simple and comes directly from the source. In fact, behind the scenes, the framework uses the find()
method that, starting from an elements' collection, searches for descendants that match a given selector. The proof is the following snippet taken from the source:
// HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); }
As I said, the use of context
doesn't always boost performance. For example, if you're selecting an element by its id, you won't have any benefits. Thus:
$('#someId', 'p')
won't improve performance compared to:
$('#someId')
Indeed, the first solution slows down the selection because it firstly needs to retrieve a potentially high number of paragraphs and then test their descendants, instead of taking advantage of the native getElementById()
.
Where it can really make a difference is when selector
is searching for a tag name or a class, or when context is an ID. Thus, a selection like the following:
$('#aDiv .red')
can be turned into this:
$('.red', '#aDiv')
One important point to keep in mind is that when it comes to performance, there isn't a rule that is always true. It really depends on several factors, like how many and what are the nodes of your DOM, and the browser. So, the best advice I can give is to test your selectors and see what's the best solution by applying the knowledge you're (hopefully) acquiring reading this book.