Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dom Navigation in JavaScript

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

PropertyDescriptionExample
parentNodeAccess the parent nodeelem.parentNode
childrenGet an HTMLCollection of child elementselem.children
firstChildGet the first child node (can be text)elem.firstChild
lastChildGet the last child nodeelem.lastChild
firstElementChildGet the first child element (ignores text nodes)elem.firstElementChild
lastElementChildGet the last child elementelem.lastElementChild
nextSiblingGet the next sibling node (can be text)elem.nextSibling
previousSiblingGet the previous sibling nodeelem.previousSibling
nextElementSiblingGet the next sibling elementelem.nextElementSibling
previousElementSiblingGet the previous sibling elementelem.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, nextSibling include all node types (elements, text, comments).

  • Properties like firstElementChild, nextElementSibling only 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 CaseProperty
Get parent elementparentNode
Get all child elementschildren
Get first child elementfirstElementChild
Get next sibling elementnextElementSibling
Get previous sibling elementpreviousElementSibling

Want me to show how to use DOM navigation for dynamic list manipulation or create a breadcrumb trail?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql