Relationship Between Elements

Get introduced to DOM traversal and the different relationships between DOM elements.

Introduction

jQuery allows us to traverse up, down, and sideways in the DOM tree when given the initial selectionThe element selected via a selector.. Using the jQuery interface, we can easily traverse through a web page to find elements based on their relationship with other elements. This process makes querying for target elements more convenient.

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.

  • HTML
  • Output
html
output

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 and p.
  • 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 and p.

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 and ul.

Quiz: Test yourself!

The questions are based on the following web page DOM Tree:

1

What are the descendants of the element div?

A)

p, span

B)

a, button, img

C)

p, span, a, button, img

D)

div, p, span, a, button, img

Question 1 of 50 attempted