jQuery Traversing
So far, the jQuery selectors we've seen only allow us to choose elements below in the DOM tree. However, there are times when you need to choose a parent or ancestor element, which is where jQuery's DOM traversal functions come in handy. We can simply navigate up, down, and around the DOM tree using these traversal techniques.
One of the most prominent aspects of jQuery is DOM traversal. To get the most out of it, you must first grasp the relationships between the elements in a DOM tree.
The figure above depicts the parent/child connections between the elements:
-
The
<div>
element's parent is the<body>
element, and everything inside it is an ancestor. The contained<div>
element is a child of the<body>
element and the parent of the<h1>
,<p>
, and<ul>
elements. -
Because they share the same parent, the elements
<h1>
,<p>
, and<ul>
are siblings. -
The
<h1>
element is a descendent of the div> element and a child of the<body>
element. There are no offspring for this element. -
The
<p>
element is the parent of the<em>
element, a descendant of the<div>
element, and a child of the<body>
element. The contained<em>
element is a descendent of the<div>
and<body>
elements and a child of this<p>
element. -
The
<ul>
element is also the parent of the<li>
elements, the child of the<div>
element, and the descendant of the<body>
element. The contained<li>
elements are the<ul>
element's child and a descendent of the<div>
and<body>
components. Furthermore, both<li>
elements are siblings.
Traversing the DOM Tree
Now that you have understood the logical relationships between the elements in a DOM tree. In the upcoming chapters you will learn how to perform various traversing operations such as traversing up, down and sideways the DOM tree using the jQuery.