Nearby lessons
11 of 14JavaScript HTML DOM Navigation
π What is DOM Navigation?
DOM Navigation means moving through the HTML elements or nodes using JavaScript. This is helpful when you want to access parents, children, or siblings of any element dynamically.
π³ DOM Nodes
In the DOM (Document Object Model), every HTML element is treated as a node. There are different types of nodes, such as element nodes, text nodes, and comment nodes.
You can use nodeName and nodeType to understand what type of node it is.
Common node types:
1 = Element node
3 = Text node
Code Example
π¨βπ©βπ§βπ¦ Node Relationships
HTML nodes are connected like a family tree. A node can have a parent, children, and siblings.
Useful Properties:
parentNode β returns the parent of the node.
childNodes β returns a list of child nodes.
firstChild β returns the first child node.
lastChild β returns the last child node.
Code Example
βοΈ Navigating Between Nodes
You can move between elements in the DOM using sibling properties.
Useful Properties:
nextSibling, previousSibling β access next/previous node (can be text).
nextElementSibling, previousElementSibling β access next/previous element (ignores text nodes).
Code Example
πΆ Child Nodes and Node Values
You can access children using childNodes, and get their values using nodeValue.
Note: Text inside an element is stored as a text node (nodeType = 3).