How to traverse the DOM?
In JavaScript, traversing the DOM means moving through the DOM tree to access parent, child, and sibling elements relative to a given node.
Here are the main ways to traverse the DOM:
1. Parent Traversal
element.parentNodeβ Gets the parent node (can be an element, text, or document).element.parentElementβ Gets the parent element (only if itβs an element).
let child = document.querySelector(".child");
console.log(child.parentNode); // parent node
console.log(child.parentElement); // parent element
2. Child Traversal
element.childNodesβ Returns all child nodes (including text and comments).element.childrenβ Returns only element children (HTMLCollection).element.firstChild/element.lastChildβ First/last node (could be text).element.firstElementChild/element.lastElementChildβ First/last element.
let parent = document.querySelector(".parent");
console.log(parent.children); // only element children
console.log(parent.firstElementChild); // first element child
console.log(parent.lastElementChild); // last element child
3. Sibling Traversal
element.nextSibling/element.previousSiblingβ Any node.element.nextElementSibling/element.previousElementSiblingβ Only element siblings.
let item = document.querySelector(".item");
console.log(item.nextElementSibling); // next element sibling
console.log(item.previousElementSibling); // previous element sibling
4. Other Useful Traversals
element.closest(selector)β Finds the nearest ancestor that matches a selector.element.querySelector(selector)β Finds the first matching descendant.element.querySelectorAll(selector)β Finds all matching descendants.
let btn = document.querySelector(".btn");
console.log(btn.closest(".container")); // nearest ancestor with class "container"
β Summary:
- Up:
parentNode,parentElement,closest() - Down:
children,firstElementChild,lastElementChild,querySelector - Sideways:
nextElementSibling,previousElementSibling
No comments yet! You be the first to comment.
