DOM Navigation: Parent, Child & Sibling Nodes

In this article, we’ll learn how to navigate around the DOM with properties like parentNode, childrenNode, nextElementSibling, etc.

I. Parent, Child, and Sibling Nodes

A subnode of a given node is called a child node, and the given node is parent node.

Sibling nodes have the same hierarchical level under the same parent node.

For example, we have the following code

<div class="list">
    <h2 class="title">Items</h2>
    <ul class="items">
        <li class="item">Item 1</li>
        <li class="item">Item 2</li>
        <li class="item">Item 3</li>
    </ul>
    <p>Hello world</p>
</div>

In this example, div is a parent node, ul is the child node and h2 is the sibling node.

II. Parent node

To call parent node, we use parentNode or parentElement.

For example, we exame the parent node and change the text color to red.

const ul = document.querySelector(".items");

// parentNode
console.log(ul.parentNode)
ul.parentNode.style.color = "red";

III. Child node

To access child node, we use children.

For example, to access item 2 in the list, we use .children[1]

const ul = document.querySelector(".items");

// childNode
console.log(ul.children[1])

We also have other properties

  • firstElementChild
  • lastElementChild

For example, to access the last item in the list:

const ul = document.querySelector(".items");

// childNode
console.log(ul.firstElementChild)

IV. Sibling node

With sibling, we have the following properties:

  • nextElementSibling
  • previousElementSibling

Example

const ul = document.querySelector(".items");

// siblingNode
console.log(ul.previousElementSibling)