Episode 8 of 18
Traversing the DOM (part 2)
Navigate between sibling elements with nextSibling, previousSibling, and their element-only counterparts.
Traversing the DOM (part 2)
In part 1 you moved up and down the tree (parent/children). Now let us move sideways — accessing sibling elements that share the same parent.
Sibling Navigation
<ul>
<li>Ryu</li>
<li>Ken</li>
<li>Yoshi</li>
</ul>
var ken = document.querySelectorAll('li')[1]; // Second <li>
console.log(ken.nextElementSibling.textContent); // "Yoshi"
console.log(ken.previousElementSibling.textContent); // "Ryu"
Node vs Element Siblings
| All Nodes | Elements Only |
|---|---|
nextSibling | nextElementSibling |
previousSibling | previousElementSibling |
nextSibling might return a whitespace text node. nextElementSibling skips text nodes and returns the next element — which is nearly always what you want.
Null at the Boundaries
var first = document.querySelector('li');
console.log(first.previousElementSibling); // null — no sibling before the first
var last = document.querySelector('li:last-child');
console.log(last.nextElementSibling); // null — no sibling after the last
Walking Through All Siblings
var current = document.querySelector('ul').firstElementChild;
while (current) {
console.log(current.textContent);
current = current.nextElementSibling;
}
// Output: "Ryu", "Ken", "Yoshi"
Combining Traversals
var item = document.querySelector('.special');
// Go up to parent, then to the next sibling of parent
var nextSection = item.parentElement.nextElementSibling;
// Go to first child of that sibling
var firstInNext = nextSection.firstElementChild;
Key Takeaways
nextElementSiblingandpreviousElementSiblingmove between sibling elements- They return
nullwhen there is no next or previous sibling - Always use the "Element" versions to skip whitespace text nodes
- Combine parent, child, and sibling traversals to reach any element from any other