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)

Selecting by position using filters (Should know)


This recipe is the first that describes other types of selectors called filters. We've already seen some selectors that are based on the relation with other elements, but in this section we'll meet those that are under the filter category.

Getting ready

As the name suggests, these selectors work with other type of selectors, implicitly or explicitly like the attribute ones, to reduce further the set of matched elements. You can easily recognize them because they start with a semicolon sign (:). Some of them accept an argument that is passed inside the parentheses. The filters presented in this section help us by reducing elements based on their index inside the collection retrieved (not of the DOM) using the selectors already processed.

The selectors belonging to this category are as follows:

Name

Syntax

Description

Equal to

selector:eq(index)

(for example, div:eq(1))

Selects the element that has a position equal to index+1.

Even

selector:even

(for example, li:even)

Selects all of the even-indexed elements of the retrieved collection.

First

selector:first

(for example, .bold:first)

Selects just the first element of the set match.

Greater than

selector:gt(index)

(for example, li:gt(3))

Selects all of the nodes with a position greater then index+1.

Last

selector:last

(for example, input[class]:last)

Selects the last element of the retrieved collection.

Less than

selector:lt(index)

(for example, .bold:lt(2))

Selects the nodes having position less then index+1.

Odd

selector:odd

(for example, h3:odd)

Selects odd-indexed elements of the retrieved collection.

Tip

Now that you've read these filters, consider this: :eq, :gt, and :lt also accept a negative index. In that case, the elements are filtered counting backwards from the last element. So for example, if you filter a collection using :eq(-1), you'll have the same element as if you applied :last().

Keep in mind that the index of a collection starts from 0. So, the first element of the matched collection has index 0, the second element has index 1, and so on. Thus, the Even selector will counter-intuitively choose the odd-positioned elements because of their even indexes. For example, the Even selector will collect the first, third, fifth and so on elements of a collection because they have odd indexes (that is: 0, 2, 4, and so on). In conclusion, remember that Even and Odd are related to the elements' index inside the collection, not their position.

How to do it...

Our goal is to use some of the listed filters. To do that, we'll use a list and apply a red color to the text of the odd-indexed list items having class bold. In addition, we'll hide the first item, and also replace the text of the items with a position greater than 2. To perform these tasks, follow these steps:

  1. Create a copy of the template.html file and rename it as position-filters.html.

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

    <ul>
        <li>First</li>
        <li class="bold">Second</li>
        <li>Third</li>
        <li>Fourth</li>
        <li>Fifth</li>
    </ul>
  3. Edit the <head> section of the page adding this code:

    <script>
        $(document).ready(function() {
            $('li.bold:odd').css('color', '#FF0A27');
            $('li:first').hide();
            $('li:gt(2)').text('Replaced!');
        });
    </script>
  4. Save the file and open it with your favorite browser.

How it works...

Since these filters are quite simple, also the code has been built to just give you a quick example of what they do. As usual, in the first step we set up a new file using template.html as the base file. In second step, we created an unordered list with five elements, with the second item having a bold class. Then, we wrote our little function.

The first selection retrieves all of the <li> instances having class bold in the page, and then filters the collection further using the Odd filter to only retain those having an odd index. Once done, it applies a red color to the font using the jQuery's css() method. If you already loaded the page, you must have noticed that none of the elements were actually red. This happens because there is just one list item having class bold, so there aren't odd-indexed elements (recalling that the first element has index 0). Thus, the selection returns an empty collection and the style isn't applied at all.

Using the First filter, the second line selects the first element among all of the list items of the page and then hides it. So, since there is just one list in our document, it corresponds to the element having text First. In fact, looking at the page you should see just four items instead of the five that we set up.

In the third and last selection, we collect the list items having an index position greater than three (remember the 0-based positioning). Thus, the retrieved nodes are Fourth and Fifth. Once retrieved, we replace their text with Replaced! using the jQuery's text() function.