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)

Multiple selectors at once (Should know)


This section will teach you how to use more than one selector, and it doesn't matter if they're of the same or different kind, in a single call. The goal of the task is to print on the console the length of the retrieved collections.

How to do it...

This task can be achieved by performing the following instructions:

  1. Create a copy of the template.html file and rename it as multiple-selectors-at-once.html.

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

    <h1 id="title" class="bold red">Multiple selectors at once</h1>
    <div id="container" class="wrapper">
        This example shows you the use of Multiple selector.
        <p id="description" class="red">Using it you'll have better performance, so adopt it when possible.</p>
        <p id="note" class="green">This is a good note!</p>
    </div>
    <div class="wrapper">
        <h2>jQuery is so cool!</h2>
        <p class="red">I'm yet another paragraph</p>
    </div>
  3. Edit the <head> section of the page adding this code:

    <script>
        $(document).ready(function() {
            console.log($('#container, #note').length);
            console.log($('.wrapper, div').length);
            console.log($('p, h1.red, #title').length);
        });
    </script>
  4. Save the file and open it with your favorite browser.

How it works...

So far, we've seen four types of selectors: All, Id, Class, and Element. Now, it's time to see how we can use them in a single selection to apply the same effect or function. In this way, our website will gain in performance because the DOM is traversed only once. Thus, we'll have once traversing for the N used selectors, instead of N traversing, once for each selector.

To see the multiple selectors in action, in the second step, we've added a higher number of elements to the DOM. Some of them have an id, some have a class, others both and others just nothing. This will help us to use selectors of different type and to highlight the power of the multiple selectors.

To use it, we've to just add a comma after our selector. You can see it as the OR logical operator inside an expression. There isn't a limit for the usable selectors, therefore we can use as many of them as we like. Just remember that if an element has more than one match, it's retrieved once. jQuery takes care of wiping out all of the duplicates for us. Moreover, the order of the DOM elements returned may not be identical to our selectors, as they will be collected in order of appearance inside the document.

In the first statement of the anonymous function, we're asking to retrieve all of the elements having either id container or note. Then, we print the size of the collection inside the jQuery object accessing the length property. The line $('#container, #note') produces 2 as a result because jQuery retrieves <div id="container" class="wrapper"> and <p id="note" class="green">.

The second line requires elements having class wrapper plus all of the <div> instances. The first selector matches only <div id="container" class="wrapper"> while the second matches the two <div> instances of the page. Recalling what you've learned a few moments ago, jQuery will delete all of the duplicates for us. Thus, in this case too the printed value is 2 because one of the two <div> instances appears twice in the collection.

In the third and last statement, we used the Element selector to retrieve all of the paragraphs, the tag name together with the Class selector to retrieve the <h1> having class red, and the ID selector to retrieve the element having ID title. If the previous examples were clear enough, it isn't hard to understand that the console will print 4. In fact, the paragraphs found are three, there isn't a match for the second selector and the third picks the only <h1> of the page.