The jQuery selectors we've seen so far only allow us to select elements downward in the DOM tree. However, there are many occasions when you need to select a parent or ancestor element; this is where jQuery's DOM traversal methods come into play. With these traversal methods, we can navigate up, down, and around the DOM tree very easily.
DOM traversing is one of the key features of jQuery. To utilize it effectively, you need to understand the relationships between elements in a DOM tree.
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
The HTML code shown in the example above can be depicted using the following DOM tree:
The illustration above demonstrates the relationships of parent and child elements:
<body>
element serves as the parent to the <div>
element and as an ancestor to all elements contained within it. The enclosed <div>
element functions as the parent to the <h1>
, <p>
, and <ul>
elements, and as a child of the <body>
element.<h1>
, <p>
, and <ul>
are considered siblings, sharing the same parent.<h1>
element acts as a child of the <div>
element and as a descendant of the <body>
element. This element does not contain any children.<p>
element serves as the parent to the <em>
element, as a child of the <div>
element, and as a descendant of the <body>
element. The <em>
element within it acts as a child of the <p>
element and as a descendant of both the <div>
and <body>
elements.<ul>
element acts as the parent to the <li>
elements, as a child of the <div>
element, and as a descendant of the <body>
element. The <li>
elements within it act as children of the <ul>
element and as descendants of both the <div>
and <body>
elements. Additionally, the two <li>
elements are considered siblings.Note: In logical relationships, an ancestor is a parent, grandparent, great-grandparent, and so on. A descendant is a child, grandchild, great-grandchild, and so on. Sibling elements are those which share the same parent.
Having grasped the logical relationships among elements within a DOM tree, you'll now delve into performing different traversal operations using jQuery. These operations include moving up, down, and sideways within the DOM tree.
In the next chapter, you'll explore selecting parent elements in a DOM tree.