jQuery Traversing

From our previous tutorial we’ve seen that jQuery selectors only allow us to select the elements down the DOM tree. However, in some occasions where you need to select a parent or ancestor element; this is the point where jQuery's DOM traversal methods come into play. We can go up, down, and all around the DOM tree very easily with these traversal methods.

 

Document Object Model

Document Object Model (DOM) traversing is one of the important features of the jQuery. To enjoy these features, you need to understand the relationships between the elements in a DOM tree.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML DOM Tree Sample</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<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>
</html>

 

The HTML code shown in the above example can be represented by the following DOM tree:

 

The diagram above shows the parent/child relationships between the elements:

  • The <body> element is the ‘parent’ of the <div> element, and an ‘ancestor’ of all that is inside of it. Also, the enclosed <div> element is the ‘parent’ of <h1>, <p> and <ul> elements, and a ‘child’ of the <body> element.
  • Also, elements <h1>, <p> and <ul> are ‘siblings’, because they share the same parent.
  • The <h1> element is a ‘child’ of the <div> element and also, a ‘descendant’ of the <body> element. The element in question does not have any children.
  • The <p> element is the ‘parent’ of <em> element, ‘child’ of the <div> element as well as a ‘descendant’ of the <body> element. The containing <em> element is a ‘child’ of this <p> element as well as a ‘descendant’ of the <div> and <body> element.
  • lastly, the <ul> element is the ‘parent’ of the <li> elements, ‘child’ of the <div> element as well as a descendant of the <body> element. The containing <li> elements can be known as the ‘child’ of this <ul> element as well as a descendant of the <div> and <body> element. therefore, both the <li> elements are siblings.

 

Traversing the DOM Tree

So far you’ve been introduced to the logical relationships between the elements in a DOM tree. In subsequent tutorials, you will learn how to perform various traversing operations including traversing up, down, and sideways the DOM tree using the jQuery.