Relationship Between Elements
Get introduced to DOM traversal and the different relationships between DOM elements.
We'll cover the following
Introduction
jQuery allows us to traverse up, down, and sideways in the DOM tree when given the
Different relationships between elements
The different relationships between elements in the DOM are:
- Parents
- Children
- Siblings
- Ancestors
- Descendants
Ancestors include parents, grandparents, and so on all the way up to the DOM root node.
Descendants include children, grandchildren, and so on all the way down to the DOM leaf nodes.
jQuery has several useful methods that access elements based on these relationships.
Example
To understand the relationships between elements in more detail, take a look at a simple web page below. For the sake of simplicity, we will be looking at the elements between lines 5-18.
A DOM tree helps visualize relations between different web page elements. The corresponding DOM tree for the above web page above is given below.
The relationships between different elements are as follows:
Div
- Parent of
ul
andp
. - Ancestor of all other elements.
p
- Child and descendant of
div
. - Sibling of
ul
. - Parent and ancestor of
span
.
span
- Child of
p
. - Descendant of
div
andp
.
ul
- Child and descendant of
div
. - Sibling of
p
. - Parent and ancestor of both
li
.
li
Both li
elements are:
- Children of
ul
. - Siblings of each other.
- Descendants of
div
andul
.
Quiz: Test yourself!
The questions are based on the following web page DOM Tree:
What are the descendants of the element div
?
p
, span
a
, button
, img
p
, span
, a
, button
, img
div
, p
, span
, a
, button
, img