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 hierarchy (Must know)


This chapter explains how to combine the selectors seen so far using hierarchy operators to retrieve elements by their relationship in the DOM.

Getting ready

Before we dive into the code, we should be aware of the weapons in our belt. The following is a table describing all of the selectors that belong to this category:

Name

Identifying Character

Syntax

Description

Child

>

Parent > Children

(for example, #title > .red)

Selects all direct children "Children" of the parent specified by "Parent".

Descendant

(space)

Ancestor Descendants

(for example, .wrapper .red)

Selects all descendants "Descendants" having in their ancestor list "Ancestor".

Next Adjacent

+

Prev + Next

(for example. h1 + p)

Selects all "Next" elements that are immediately after a "Prev".

Next Sibling

~

Prev ~ Siblings

(for example. .bold ~ p)

Selects all sibling "Siblings" elements that follow (not just immediately after) and have the same parent of "Prev".

Let's look at the steps to perform for this recipe.

How to do it...

To achieve the prefixed goal we need to perform these steps:

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

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

    <h1 id="title" class="bold border">Multiple selectors at once</h1>
    <div class="wrapper">
        <h2>A subtitle</h2>
        <p>This demo shows how to combine selectors based on their relationship.</p>
        <p id="description" class="border">Using it you'll have better performance, so adopt it when possible.</p>
        <span>This is a sibling span</span>
        <p id="note" class="green">This is a good note!</p>
        <span>This is yet another sibling span</span>
    </div>
    <div id="content" class="wrapper">
        <h2>jQuery is so cool!</h2>
        <p class="border">I'm yet another paragraph</p>
        <ul>
            <li>The first of the list</li>
            <li>I'm the second, not bad!</li>
            <li>Third list item here</li>
        </ul>
    </div>
  3. Edit the <head> section of the page adding this code:

    <script>
        $(document).ready(function() {
            $('div > .border').css('border', '2px solid #000000');
            $('#content li').css('color', '#FF0A27');
            $('h2 + p').css('margin-left', '40px');
            $('h2 ~ span').css('background-color', '#ABF9FF');
        });
    </script>
  4. Save the file and open it with your favorite browser. It should look like the following screenshot:

How it works...

This recipe has been built to use all of the discussed hierarchical selectors, so you can easily fix them in your mind. Each of them targets a certain number of nodes and then assigns a style property, helping you in recognizing the selected elements at first glance.

The first statement picks up the elements having class border that are children (or direct descendant) of a <div>, that is the nodes that are just one level under their parent. The elements that match this criteria are the second <p> of the first <div>, and the <p> inside the second <div>. Once retrieved, we'll apply them a 2px width, solid and black border, as you learned in the Selecting by ID (Must know) recipe.

The second selection adopts the Descendant selector to collect all of the descendants, no matter the depth level they are, of those elements that match the first selector. In this specific case, we're choosing all of the <li> inside of a <div>. The result is a collection containing the list items inside the second <div>, to which we set the font color to red using the jQuery's css() method.

The third line of code of our anonymous function selects the paragraphs that are just after a subtitle (<h2>) and share the same parent. Those elements are moved on the right of 40px using the property margin-left. You can easily recognize them looking at the earlier screenshot.

The last selection of our example chooses all of the <span> instances positioned after a subtitle (<h2>) and applies a blue background color to them.