Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Instant jQuery Selectors

You're reading from   Instant jQuery Selectors Learn how to master the art of effectively using jQuery's selectors

Arrow left icon
Product type Paperback
Published in Aug 2013
Publisher Packt
ISBN-13 9781783282210
Length 70 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Aurelio De Rosa Aurelio De Rosa
Author Profile Icon Aurelio De Rosa
Aurelio De Rosa
Arrow right icon
View More author details
Toc

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image