Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Instant jQuery Selectors

You're reading from   Instant jQuery Selectors Learn how to master the art of effectively using jQuery's selectors

Arrow left icon
Product type Paperback
Published in Aug 2013
Publisher Packt
ISBN-13 9781783282210
Length 70 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Aurelio De Rosa Aurelio De Rosa
Author Profile Icon Aurelio De Rosa
Aurelio De Rosa
Arrow right icon
View More author details
Toc

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:

  1. Create a copy of the child-filters.html file and rename it as context-matters.html.

  2. Edit the <head> section of the page adding this code:

    <script>
        $(document).ready(function() {
            $('li', '#content').css('border', '2px solid #000000');
        });
    </script>
  3. 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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image