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)

Traversing DOM SubTrees (Become an expert)


Now that the book is almost at its end, you should be convinced of the jQuery's power. However, I can guarantee that we've touched only the tip of the iceberg because with jQuery you can really, really do more than that.

This section describes how many, and what are the methods that can be applied to a collection to find elements starting from a matched set. One of these methods is find(); we have come across it several times.

Getting ready

The Tree Traversal methods are:

Name

Description

children()

Retrieves the children of every element in the previously created collection. If a selector is passed, only the children that match it are retrieved.

closest()

Gets the first element that matches the given selector for every element in the collection. The search is performed starting from the element itself and then traversing up through its ancestors in the DOM tree.

find()

Picks up the descendants of each element in the collection that match the given, mandatory selector.

next()

Collect the immediately following sibling of each element in the set of matched elements. It can optionally take a selector, in which case only the next sibling that matches is taken.

nextAll()

For each collection's element retrieves the following siblings, optionally filtered by a selector.

nextUntil()

Similar to nextAll(), but it stops before the element matched by the selector.

offsetParent()

Gets the closest ancestor element that is positioned. An element is positioned if it has a CSS position attribute of relative, absolute, or fixed.

parent()

For every element in the previously created collection, gets the parent. It can optionally accept a selector.

parents()

Similar to parent() but it collects all of the ancestors, not just the parent. It optionally accepts a selector to filter the nodes by testing whether they match it.

parentsUntil()

Selects the ancestors of each element in the collection, up to but not including the element matched by the selector.

prev()

Collects the immediately preceding sibling of each element in the collection. It can optionally accept a selector.

prevAll()

For every element in the previously created collection, gets all preceding siblings. It can optionally accept a selector.

prevUntil()

Similar to prevAll(), but it stops before the element matched by the selector.

siblings()

Gets the siblings of each element in the set of matched elements, optionally filtered by a selector.

How to do it...

As you can see, there are a lot of methods belonging to this category. In the following recipe, I'll show you the use of two of them of different type so that you can strongly fix the concepts in your mind.

To build the example, follow these steps:

  1. Create a copy of the template.html file and rename it as traversing-methods.html.

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

    <div id="grandfather">
        <div id="father">
            <div id="child-1" class="child">I'm the child of #father!</div>
            <div id="child-2" class="child">
                I'm the second child of #father
                <div id="descendant">What a great hierarchy!</div>
            </div>
        </div>
        <div class="uncle">
            First uncle here!
        </div>
        <div class="uncle">
            Second uncle
        </div>
        <div class="uncle">
            Yet another uncle
        </div>
    </div>
  3. Edit the <head> section adding the following code just after the <title> tag:

    <style>
        .child {
            background-color: #ED9566;
        }
        .uncle {
            background-color: #66ED66;
        }
        #descendant {
            background-color: #E01B5D;
        }
    </style>
  4. Edit the <head> section of the page adding this code:

    <script>
        $(document).ready(function() {
            $('#grandfather').find('.child').css('margin-left', '40px');
            var $ancestors = $('#descendant').parents();
            for(var i = 0; i < $ancestors.length; i++) {console.log('Element ' + $ancestors[i].tagName + ' with id ' + $ancestors[i].id);
            }
    </script>
  5. Save the file and open it with your favorite browser.

How to do it...

In the first line of the anonymous function, we first selected the element having id grandfather and then used the find() method to search, among its descendants, those having the class child applied. Looking at our code, you can see that we retrieved two <div> instances, the first having ID child-1 and the second with ID child-2. Once retrieved, we applied a left margin of 40px to them so, when opening the file in your browser, you should see these elements shifted from the left side of the page.

The goal of the next block, that is slightly more complex than the previous, is to print on the console the tag name and the id of the ancestors of the element with ID descendant. To perform this task, in the second line we selected the element relying on its id and then, using the parents() method, we retrieved its ancestors. Once done, we cached the collection in a variable called $ancestors to improve performances.

Then, we created a loop to iterate over the ancestors and print on the console the tag name and the id of each element. Now, you should wonder why I chose to print also the tag name and not only the id. The reason is that we used the parents() method, so the collection includes elements such as <body> and <html> that do not have an id. Therefore, if we printed only the ID, we wouldn't be able to recognize the iterated element. On the contrary, looking at the console, you should see the following output:

Element DIV with id child-2
Element DIV with id father
Element DIV with id grandfather
Element BODY with id
Element HTML with id