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
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

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
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