In this article, we’ll learn how to navigate around the DOM with properties like parentNode, childrenNode, nextElementSibling, etc.
A subnode of a given node is called a child node, and the given node is the 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.
To call parent node, we use parentNode
or parentElement
.
For example, we examine 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";
To access the 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.
For example, to access the last item in the list:
const ul = document.querySelector(".items");
// childNode
console.log(ul.firstElementChild)
With siblings, we have the following properties:
Example
const ul = document.querySelector(".items");
// siblingNode
console.log(ul.previousElementSibling)