By the end of this lesson, learners will be able to:
parentNode, childNodes, children, nextElementSibling, and previousElementSiblingOnce you select an element, you often need to move around the DOM tree:
✅ go to its parent
✅ get its children
✅ move to its siblings
This is called DOM traversal and it is crucial for:
Let’s break down the most useful DOM traversal properties:
parentNodeGives you the immediate parent of an element.
let item = document.getElementById("my-item");
let parent = item.parentNode;
childNodesReturns all child nodes of an element, including:
let children = parent.childNodes;
⚠️ Be careful: text nodes and whitespace count too!
childrenA cleaner version: returns only child elements, ignoring whitespace/text.
let children = parent.children;
✅ This is usually what you want for working with lists or menus.
nextElementSiblingGives you the next element on the same level.
let next = item.nextElementSibling;
previousElementSiblingGives you the previous element on the same level.
let prev = item.previousElementSibling;
Think of the DOM like a family tree:
DOM traversal lets you walk the tree in any direction.
HTML:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li id="current">Item 3</li>
<li>Item 4</li>
</ul>
CSS:
.highlight {
background-color: yellow;
}
JavaScript:
let current = document.getElementById("current");
let previous = current.previousElementSibling;
if (previous) {
previous.classList.add("highlight");
}
✅ Result: Item 2 will get a yellow background.
✅ If there is no previous element (for the first item), nothing happens.
let next = current.nextElementSibling;
if (next) {
next.classList.add("highlight");
}
let list = document.querySelector("ul");
for (let item of list.children) {
item.style.fontWeight = "bold";
}
HTML:
<ul id="nav">
<li>Home</li>
<li>About</li>
<li id="active">Contact</li>
<li>Blog</li>
</ul>
Task:
Example JavaScript:
let active = document.getElementById("active");
let prev = active.previousElementSibling;
if (prev) {
prev.style.color = "green";
}
let next = active.nextElementSibling;
if (next) {
next.style.color = "blue";
}
| Property | What it Does |
|---|---|
parentNode | Finds the parent of an element |
children | Returns only element children |
childNodes | Returns all nodes (elements, text, whitespace) |
nextElementSibling | Moves to the next sibling element |
previousElementSibling | Moves to the previous sibling element |