DOM Tree and Nodes — Complete Guide
In this tutorial, you will learn about DOM Tree and Nodes. We cover key concepts, practical examples, and best practices to help you master this topic.
DOM tree nodes are the building blocks of the document — element nodes, text nodes, attribute nodes, and comment nodes form a hierarchical parent-child structure that JavaScript can traverse and manipulate.
What You'll Learn
- The different types of DOM nodes: element, text, comment, document, and attribute
- How the node tree hierarchy works with parent, child, and sibling relationships
- How to inspect node types using the nodeType property
- Why understanding nodes matters for DOM traversal and manipulation
Why It Matters
Every DOM operation — selecting, creating, moving, or deleting content — works with nodes. Confusing element nodes with text nodes causes subtle bugs. Knowing the node types helps you write robust code that handles the DOM structure correctly.
Real-World Use
- A rich text editor must distinguish element nodes (bold, italic) from text nodes (the actual words)
- A web scraper needs to filter out comment nodes when extracting content
- A Virtual Dom implementation must map each real DOM node to its virtual counterpart
flowchart TD A[Document Node] --> B[Document Type Node doctype] A --> C[Element Node html] C --> D[Element Node head] C --> E[Element Node body] E --> F[Element Nodes h1, p, div] F --> G[Text Nodes Hello, World] E --> H[Comment Nodes ] D --> I[Element Node title] I --> J[Text Node Page Title]
Understanding DOM Node Types
The DOM specification defines 12 node types, but you will encounter only a handful in everyday development. Each node has a nodeType property that returns an integer constant identifying its type.
Element Nodes (nodeType === 1)
Element nodes represent HTML tags. They are the most common node type you will work with. Every <div>, <p>, <span>, <a>, and <img> tag becomes an element node.
const div = document.createElement('div');
console.log(div.nodeType);
console.log(div.nodeName);
// Existing element from the page
const body = document.body;
console.log(body.nodeType);
console.log(body.nodeName);
Expected output: 1 for both div and body elements. nodeName returns DIV and BODY in uppercase.
Text Nodes (nodeType === 3)
Text nodes contain the actual text content of an element. When you write <p>Hello</p>, the text "Hello" is a child text node of the paragraph element. Text nodes cannot have children.
const p = document.createElement('p');
p.textContent = 'Hello, World!';
document.body.appendChild(p);
// Access the text node child
const textNode = p.firstChild;
console.log(textNode.nodeType);
console.log(textNode.nodeValue);
Expected output: 3 for the text node type. The nodeValue returns "Hello, World!".
Comment Nodes (nodeType === 8)
HTML comments become comment nodes in the DOM. They are invisible to users but can appear if you traverse all child nodes.
// This HTML comment <!-- this is hidden -->
// appears as a comment node in the DOM
const div = document.createElement('div');
div.innerHTML = '<!-- comment -->visible text';
console.log(div.childNodes.length);
console.log(div.childNodes[0].nodeType);
console.log(div.childNodes[1].nodeType);
Expected output: 2 child nodes. The first has nodeType 8 (comment), the second has nodeType 3 (text).
Document Node (nodeType === 9)
The document node is the root of the entire DOM tree. It represents the entire page and is accessed through the global document object.
console.log(document.nodeType);
console.log(document.nodeName);
console.log(document.childNodes.length);
Expected output: 9 for the document node type. The nodeName is #document. The childNodes count shows at least one child (the document type and html element).
Important Node Properties
Every node shares these core properties:
nodeType— integer indicating the node type (1 for element, 3 for text, 8 for comment, 9 for document)nodeName— the name of the node (tag name for elements,#textfor text,#commentfor comments,#documentfor document)nodeValue— the value of the node (null for elements, the text content for text nodes, the comment text for comments)childNodes— a live NodeList of all child nodes (including text and comments)parentNode— the parent node in the tree
function describeNode(node) {
const types = {
1: 'element',
3: 'text',
8: 'comment',
9: 'document'
};
console.log(`Node: ${node.nodeName}, Type: ${types[node.nodeType] || node.nodeType}`);
}
describeNode(document);
describeNode(document.body);
const text = document.createTextNode('test');
describeNode(text);
Expected output: Three lines showing the document node (type 9), body element node (type 1), and the created text node (type 3).
Common Mistakes
- Assuming childNodes only contains elements — The
childNodesproperty includes text nodes (whitespace) and comment nodes. Usechildrenif you want only element nodes. - Trying to set textContent on a text node — Text nodes do not support
textContent. UsenodeValueto read or write their content. - Forgetting that whitespace creates text nodes — Line breaks and indentation between elements in HTML produce text nodes containing whitespace. This causes unexpected childNodes counts.
- Confusing nodeName with tagName —
tagNameexists only on element nodes.nodeNameworks on all node types and returns different values for each type. - Creating an element but forgetting to append it —
createElementcreates a node in memory only. It does not appear in the DOM until you useappendChildorinsertBefore.
Practice Questions
- What nodeType value do element nodes have?
1. - How do text nodes differ from element nodes in terms of children? Text nodes cannot have children. Element nodes can have child nodes of any type.
- Why does
document.body.childNodesoften return more nodes thandocument.body.children? BecausechildNodesincludes text nodes (whitespace between elements) and comment nodes, whilechildrenreturns only element nodes. - Challenge: Write a function that recursively walks the DOM tree and logs each node's nodeName and nodeType, indented by depth level.
FAQ
Mini Project
Create an HTML page with a nested structure of divs, paragraphs, and comments. Write a script that walks the entire DOM tree recursively and prints each node's type and name with indentation. Verify that whitespace text nodes appear between elements and that comment nodes are included.
What's Next
Continue with Lesson 3: Selecting DOM Elements to learn how to find specific nodes in the tree using query selectors and traversal methods.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro