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)

Methods to filter collections (Become an expert)


We've already delved into filters, but what you probably don't know is that jQuery has methods to filter collections as well. This section describes how many and what are these methods.

Getting ready

The methods of this type are:

Name

Description

eq()

Reduces the retrieved collection to the element having position index+1.

filter()

Reduces the collection to those elements that match the given selector or pass the test function.

first()

Keeps just the first element of the collection.

has()

Reduces the set of matched elements to those that have a descendant that matches the selector or DOM element.

last()

Keeps just the last element of the collection.

map()

Each element of the collection is passed to the given function and only those that are returned are kept.

not()

Removes the collection's elements that match the given selector.

slice()

Reduces the retrieved collection to those elements having a position within a specified range.

Also consider the following note:

Tip

The jQuery documentation includes also the is() method in this category, but I didn't because its aim isn't to filter a collection, but to test it. In fact, citing the documentation, the is() method Checks the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

How to do it...

This recipe will show you the use of some of the cited methods:

  1. Create a copy of the hierarchy-selectors.html file and rename it as filter-methods.html.

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

    <script>
        $(document).ready(function() {
            console.log($('p.border').eq(-1).text());
            console.log($('div').has('ul').length);
            console.log(
                $('div').map(function(index, domElem) {
                    if ($('#note', domElem).length !== 0) {
                        return domElem;}
                })
                .length
            );
        });
    </script>
  3. Save the file and open it with your favorite browser.

How it works...

This recipe uses three of the eight methods described. Before talking about what our code does, it's worth noting that at this point of the book, some of them should be really familiar. In fact, we've already met filters called :eq, :first, :last and :not. Surprisingly, the methods having the same name, but do not act like their respective filters.

On opening the created file on your browser, you should see the following lines on the console:

I'm yet another paragraph

1

1

Let's discover why we have this output.

In the first line of our function we selected all of the paragraphs having the class border applied and then filtered using the eq() method. As you can see, it shows the use of eq() using a negative index that, as I already pointed out in the Selecting by position using filters (Should know) recipe, lets the count start from the end of the collection. We passed -1, which means we're selecting the last element of the collection. In our code there are just two paragraphs that match, but since we're choosing only the last, our final collection contains only the paragraph having text I'm yet another paragraph. Once filtered, we print on the console the text of the node using the text() method and this explains the first line of the resulting output.

The following statement selects all of the <div> instances of the page but keeps only those having a <ul> as descendant. The filter is achieved using the has() method described in the previous table. After that, we print on the console the length of the retrieved collection that is composed by just one element as you can confirm looking at the HTML code.

The third and last statement, are the more complex ones. We start again selecting all of the <div> instances of the page, but this time we reduce the set of matched elements using map(). The latter iterates over the collection elements and accepts a callback function which can take up to two arguments: the index of the current element and the element itself. Besides, within the callback function, this refers to the current DOM element. Its basic use is to return the element if you want to keep it, and null or undefined (no return is the same as returning undefined) to remove it. However, you can also return an array of data items to be inserted into the resulting set.

As a callback, we're using an anonymous function. Inside it we test if the current node has a descendant having ID note, in which case we keep the element by returning it. Once the entire collection is processed, we write the length of the new one on the console. This time too, you can see that the console shows the right value.