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)

The All selector (Must know)


With our template in place, we can start diving into the world of jQuery selectors. A selector is a string that allows you to retrieve DOM's elements. The first selector we'll look at is the All (or Universal) selector. We'll use it to apply a border to all of the page's elements.

How to do it...

To achieve our goal, perform the following steps:

  1. Create a copy of the template.html file and rename it the-all-selector.html.

  2. Inside the <body> tag, add the following HTML markup:

    <h1>The all selector</h1>
      <div>
        This example shows how to use the All selector.
        <p>As you can see, it doesn't matter we're different tags, we all have the border applied.</p>
        <span>Every tag has the border, even the body, the html and the head tag!</span>
      </div>
  3. Edit the <head> section of the page by adding the following highlighted code:

        <script src="jquery-1.10.1.min.js"></script>
        <script>
            $(document).ready(function() {
                $('*').css('border', '2px solid #000000');
            });
        </script>
    </head>
  4. Save the file and open it with your favorite browser.

How it works...

In step 2, we put some elements inside the <body> tag to have something to work with but there isn't anything special here.

Then, we created a new <script> tag where we wrote our JavaScript instructions. To call the jQuery methods, we used the $ property for brevity. It's important to add the script after the jQuery file, otherwise our code won't work because we can't use the jQuery methods before the library is loaded.

The first method used, although a little bit hidden, is the constructor. This method accepts up to two arguments and, depending on their number and type, performs different tasks. Just like other several jQuery's methods, it allows for chaining, a programming technique that lets you call several methods in a single statement. Although not restricted to this, its most common use is to select elements retrieved from the DOM (Document Object Model). In this case, it accepts two parameters, a selector and optionally a context, and returns a jQuery object containing a collection of DOM elements that match the given criteria. In our task, we used the document object as a selector and then called the ready() method relying on chaining.

Note

For the sake of brevity, I'll use returns a collection to intend a jQuery object containing a collection from now on.

The ready() method called on the document object is one of the most common statements by programmers using this library. It accepts as its only argument a function that will be executed when the ready event is fired, and that is as soon as the DOM is fully loaded. This means that inside the handler passed to ready() you can safely access all of the elements of your page. In the example shown, we've used an anonymous function but we can also define a function and then pass just the function's name.

Inside our handler we have just one statement. The first part is a call to the jQuery constructor that we've just analyzed. This time, however, we used one of the selectors available, the All selector. It's represented by an asterisk (*) and should be familiar to you if you're experienced with CSS. This choice is not casual and, as we'll discover in the next chapters, it's a frequent pattern to adopt the same convention used in CSS. As the name says, it asks jQuery to pick up all of the DOM elements of your page, even the <head> element and its children.

After we've selected all of the elements, we called the css() function to apply a 2px width, solid and black (#000000) border to the matched elements. Hence, the border is really set to all of the elements on the page, as proven by the following screenshot made using the Google Chrome developer tools:

css() accepts up to two arguments and the first is usually a CSS property name. If you pass a string with a CSS property, the method gets the value for the first element in the set of matched elements. If you pass a CSS property and a value, as we did in the recipe, the method acts on each element matched. Note that it can also accept an object as its first parameter to set more properties at once.

There's more...

Like the previous section, this short recipe gives us some points to discuss.

Alternatives to $(document).ready()

We have two more ways to call the ready() function on the document object. The first and shorter one is to write $(handler). So, if we want to rewrite our recipe using this syntax, it becomes:

$(function() {
    $('*').css('border', '2px solid #000000');
});

Another equivalent way is to write $().ready(handler). Thus, our code turns into:

$().ready(function() {
    $('*').css('border', '2px solid #000000');
});

This syntax is not recommended by the official documentation and, honestly, I've never seen it used. I've included it for completeness, though.

Avoiding $(document).ready()

In our example, we loaded the jQuery library and our script inside the <head> tag. Doing so, the loading of the page is blocked until they're completely loaded and the users won't see anything of your page. Therefore, it's better to put them just before the closing tag of body element. In this way, you'll enhance the experience of your users.

I chose to put it inside the <head> tag to have the chance to explain $(document).ready, but keep in mind that by having your scripts at the bottom of the page you can completely avoid the use of $(document).ready. In fact, at that point, all of the other elements are already in the DOM.

css() and browsers support

The CSS styles applied with the css() function are dependent on the browser's support. So, if the latter doesn't support a property you set, it simply won't work as you expected. In fact, jQuery doesn't try to overcome the limitations of a browser's style rendering with the exception of opacity. So, before using a property double-check its support among browsers.

Selectors and browsers support

Unlike the css() method, whatever selector you'll pass to jQuery, chosen among those covered in this book and listed at http://api.jquery.com/category/selectors/, it'll return the expected elements' collection regardless of the browsers support. Thus, we can use them all without worries, jQuery will watch our back.

Performance

The use of the universal selector is highly discouraged due to its bad performance. Using it, jQuery needs to traverse and select all of the DOM's nodes and, with a huge number of elements, the process is very slow. Moreover, we've seen that it retrieves elements that aren't really needed to achieve the desired goal, like the <head> tag.

Having said that, in those situations where you'll really need to retrieve all of the elements inside a node, you can always replace it in favor of the use of other methods, such as children() and find(), that usually lead to better performance.