DOM Nodes
DOM node provides several properties and methods that allow you to navigate or traverse through the tree structure of the DOM and make changes very easily.
Everything in an HTML document is a node. All nodes in the node tree can be accessed by JavaScript. New nodes can be created, and all nodes can be modified or deleted.
- The entire document is a document node
- Every HTML element is an element node
- The text inside HTML elements are text nodes
Accessing the Child Nodes
You can use the childNodes property to access all child nodes of a given element, where the first child node is assigned index 0.
Example :
If you observe above example, in NodeList we have five items instead of two. Because, whitespace such as spaces, tabs, newlines, etc. are valid characters and they form #text nodes and become a part of the DOM tree.
The childNodes returns all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use children property instead.
Example :
You can use the firstChild and lastChild properties of the DOM node to access the first and last direct child node of a node, respectively. If the node doesn’t have any child element, it returns null.
Example :
To avoid the issue with firstChild and lastChild returning #text or #comment nodes, you could alternatively use the firstElementChild and lastElementChild properties to return only the first and last element node, respectively.
Example :
Accessing the Parent Nodes
You can use the parentNode property to access the parent of the specified node in the DOM tree.
The parentNode will always return null for document node, since it doesn’t have a parent.
Example :
However, if you want to get only element nodes you can use the parentElement
Example :
var hint = document.getElementById(“hint”); console.log(hint.parentElement); // Prints: div
Accessing the Sibling Nodes
You can use the previousSibling and nextSibling properties to access the previous and next node in the DOM tree, respectively.
Example :
Alternatively, you can use the previousElementSibling and nextElementSibling to get the previous and next sibling element skipping any whitespace text nodes. All these properties returns null if there is no such sibling.
Example :