Traversing the DOM Based on Your Current Context to Acquire a New Set of DOM Elements - J Query

Problem
You have selected a set of DOM elements, and based on the position of the selections within the DOM tree structure, you want to traverse the DOM to acquire a new set of elements to operate on.

Solution

jQuery provides a set of methods for traversing the DOM based on the context of the currently selected DOM element(s).
For example, let’s examine the following HTML snippet:

Now, let’s select the second <li>element using the :eq() index custom selector:

We now have a context, a starting point within the HTML structure. Our starting point is the second <li>element. From here we can go anywhere—well, almost anywhere. Let’s see where we can go using a couple of the methodsjQuery provides for traversing the DOM. Read the comments in the code for clarification:

Keep in mind that these traversing methods produce a new wrapper set, and to return to the previous wrapper set, you can use end().

Discussion

The traversing methods shown thus far have demonstrated simple traverses. There are two additional concepts that are important to know about traversing.
The first concept and likely most obvious is that traversing methods can be chained.
Let’s examine again the following jQuery statement from earlier:

Notice that I have traversed from the second <li>element to the parent <ul>element and then again traversed from the parent element to selecting all the children elements of the <ul>element. The jQuery wrapper set will now contain all the <li>elements contained within the <ul>. Of course, this is a contrived example for the purpose of demonstrating traversing methods. Had we really wanted a wrapper set of just <li>elements, it would have been much simpler to select all the <li>elements from the get-go (e.g., jQuery('li')).

The second concept that you need to keep in mind when dealing with the traversing methods is that many of the methods will accept an optional parameter that can be used to filter the selections. Let’s take our chained example again and look at how we could change it so that only the last <li>element was selected. Keep in mind that this is a contrived example for the purpose of demonstrating how a traversing method can be passed an expression used for selecting a very specific element:

jQuery provides additional traversing methods that were not shown here.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics