Dom Navigation in JavaScript
? DOM Navigation in JavaScript
What is DOM Navigation?
DOM navigation means moving through the DOM tree by accessing related elements like parents, children, and siblings.
It lets you traverse the document structure dynamically.
Key Navigation Properties
| Property | Description | Example |
|---|---|---|
parentNode | Access the parent node | elem.parentNode |
children | Get an HTMLCollection of child elements | elem.children |
firstChild | Get the first child node (can be text) | elem.firstChild |
lastChild | Get the last child node | elem.lastChild |
firstElementChild | Get the first child element (ignores text nodes) | elem.firstElementChild |
lastElementChild | Get the last child element | elem.lastElementChild |
nextSibling | Get the next sibling node (can be text) | elem.nextSibling |
previousSibling | Get the previous sibling node | elem.previousSibling |
nextElementSibling | Get the next sibling element | elem.nextElementSibling |
previousElementSibling | Get the previous sibling element | elem.previousElementSibling |
Example: Navigating the DOM Tree
<ul id="list"> <li>Item 1</li> <li id="item2">Item 2</li> <li>Item 3</li></ul><script>const item2 = document.getElementById("item2");// Parent elementconsole.log(item2.parentNode); // <ul id="list">// Next sibling elementconsole.log(item2.nextElementSibling); // <li>Item 3</li>// Previous sibling elementconsole.log(item2.previousElementSibling); // <li>Item 1</li>// Children of parentconsole.log(item2.parentNode.children); // HTMLCollection of all <li> items</script>Text Nodes vs Element Nodes
Properties like
firstChild,nextSiblinginclude all node types (elements, text, comments).Properties like
firstElementChild,nextElementSiblingonly include element nodes (HTML tags).
Traversing Up and Down
const elem = document.querySelector(".some-element");// Move up to the grandparentconst grandparent = elem.parentNode.parentNode;// Move down to first child elementconst firstChild = elem.firstElementChild;Summary
| Use Case | Property |
|---|---|
| Get parent element | parentNode |
| Get all child elements | children |
| Get first child element | firstElementChild |
| Get next sibling element | nextElementSibling |
| Get previous sibling element | previousElementSibling |
Want me to show how to use DOM navigation for dynamic list manipulation or create a breadcrumb trail?