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.
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.
Let's define what these relationships actually mean in HTML:
Look at this simple HTML structure to visualize the 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>.
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.
jQuery provides a massive variety of methods that allow us to traverse the DOM.
The traversing methods are divided into three main categories:
In the next chapters, we will cover exactly how to perform all of these movements.
In the context of the HTML DOM tree, what is a "sibling"?