Book Image

Instant jQuery Selectors

By : Aurelio De Rosa
Book Image

Instant jQuery Selectors

By: Aurelio De Rosa

Overview of this book

jQuery's selectors is one of the most important concepts of the jQuery library. Usually, the first thing you do is to select one or more elements of a page in order to manipulate them. Therefore, to efficiently learn the usage of jQuery's selectors is one of the first steps to successfully build your website. Instant jQuery Selectors is a practical guide that will teach you how to use jQuery's selectors efficiently in order to easily select theelements of your pages to operate upon with jQuery's methods. You will go through the most common problems that you could face while developing your project and will learn how to solve them with the help of focused examples that Instant jQuery Selectors has to offer. Instant jQuery Selectors, starting from how to set up jQuery and how to choose the right version for your project, explains to you all the selectors available using a multitude of simple and practical recipes that will help you start using selectors in the right way. Reading the presented recipes you'll learn about the numerous selectors and filters of jQuery – almost 100 of them! You will see how to reuse collections, the methods to filter collections, and how to take advantage of the lesser known parameter of jQuery's constructor: context. Also, you'll discover the methods to traverse the DOM and the techniques to improve the performance of your website by just tweaking selectors. Instant jQuery Selectors is the resource to learn everything you need to know about jQuery's selectors.
Table of Contents (7 chapters)

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.