Dom Nodes in JavaScript
? DOM Nodes in JavaScript
What is a DOM Node?
A Node is the basic building block of the DOM tree.
Everything in the DOM is a node: elements, text, comments, attributes, etc.
Nodes are objects representing parts of the document.
Types of DOM Nodes
| Node Type | Description | NodeType Value (Number) |
|---|---|---|
| Element Node | Represents HTML elements (e.g., <div>) | 1 |
| Attribute Node | Represents attributes (e.g., class) | 2 |
| Text Node | Represents text inside elements | 3 |
| Comment Node | Represents comments (<!-- comment -->) | 8 |
| Document Node | Represents the entire document | 9 |
Common Node Properties
| Property | Description |
|---|---|
nodeType | Numeric code identifying the node type |
nodeName | Name of the node (tag name for elements) |
nodeValue | Value of the node (text for text nodes) |
parentNode | Reference to the parent node |
childNodes | Collection of child nodes |
firstChild | First child node |
lastChild | Last child node |
nextSibling | Next sibling node |
previousSibling | Previous sibling node |
Example: Inspecting Node Types
<div id="myDiv">Hello <span>World</span><!-- comment --></div><script>const div = document.getElementById("myDiv");// Element nodeconsole.log(div.nodeType); // 1console.log(div.nodeName); // "DIV"// Text node (first child)const textNode = div.firstChild;console.log(textNode.nodeType); // 3console.log(textNode.nodeValue); // "Hello "// Comment node (last child)const commentNode = div.lastChild;console.log(commentNode.nodeType); // 8console.log(commentNode.nodeValue); // " comment "</script>Manipulating Nodes
You can create nodes with
document.createElement(),document.createTextNode().Nodes can be inserted or removed using DOM methods like
appendChild(),removeChild().
const newText = document.createTextNode("New text node");div.appendChild(newText);Summary
DOM Nodes represent every part of the document.
Key types: element nodes, text nodes, comment nodes, etc.
Understanding nodes helps in fine-grained manipulation of HTML.
Want to learn how to create and insert different node types dynamically or traverse nodes recursively?