jQuery Traversing

jQuery Traversing

jQuery traversing simply means "moving through" your HTML elements.

It is used to find or select HTML elements based on their relationship to other elements.

You start with one initial selection, and then move through that selection until you reach your desired elements.


The DOM Tree

To understand traversing, you must understand the DOM (Document Object Model) tree.

The DOM tree represents all your HTML elements grouped together by their relationships.

Imagine a family tree, where elements can be parents, children, or siblings.


Element Relationships

Let's define what these relationships actually mean in HTML:


Traversing the DOM Example

Look at this simple HTML structure to visualize the family tree.

HTML Family Tree:

<div>
  <ul>
    <li>
      <span>Hello World!</span>
    </li>
  </ul>
</div>

In this example:

The <div> element is the parent of <ul>, and an ancestor of everything inside of it.

The <ul> element is the parent of <li>, and the child of <div>.

The <li> element is the parent of <span>, the child of <ul>, and a descendant of <div>.

The <span> element is the child of <li>, and a descendant of both <ul> and <div>.


Why Traverse the DOM?

Sometimes selecting an element by its ID or Class is impossible or inefficient.

For example, if you have a list of ten identical buttons, how do you modify only the text next to the button that was clicked?

You would use traversing to say: "When this button is clicked, find its sibling paragraph and change the color."

This keeps your code flexible and highly dynamic.


Traversing Categories

jQuery provides a massive variety of methods that allow us to traverse the DOM.

The traversing methods are divided into three main categories:

  1. Traversing Up: Finding ancestors.
  2. Traversing Down: Finding descendants.
  3. Traversing Sideways: Finding siblings.

In the next chapters, we will cover exactly how to perform all of these movements.


Exercise 1 of 1

?

In the context of the HTML DOM tree, what is a "sibling"?