DOM Nodes

Understanding the building blocks of the DOM

🌳 What are DOM Nodes?

DOM Nodes are the building blocks of the DOM tree. Everything in HTML is a node - elements, text, attributes, and comments.


// Create a new text node
let textNode = document.createTextNode('Hello World');

// Create a new element node
let elementNode = document.createElement('p');
                                    

Try it:

Types of Nodes

📄

Element Nodes

HTML elements like div, p, span

document.createElement('div')
📝

Text Nodes

Text content inside elements

document.createTextNode('text')
🏷️

Attribute Nodes

Element attributes like id, class

element.setAttribute('id', 'myId')
💬

Comment Nodes

HTML comments in the document

document.createComment('comment')

🔹 Creating Nodes

Create different types of nodes:

// Create element node
let div = document.createElement('div');

// Create text node
let text = document.createTextNode('Hello World');

// Create comment node
let comment = document.createComment('This is a comment');

// Append text to element
div.appendChild(text);

// Add to document
document.body.appendChild(div);

Interactive Example:

🔹 Node Properties

Every node has useful properties:

// Node type (1=Element, 3=Text, 8=Comment)
console.log(node.nodeType);

// Node name (tag name for elements)
console.log(node.nodeName);

// Node value (text content for text nodes)
console.log(node.nodeValue);

// Parent node
console.log(node.parentNode);

// Child nodes (includes text nodes)
console.log(node.childNodes);

Interactive Example:

This is a test paragraph

🔹 Manipulating Nodes

Add, remove, and modify nodes:

// Append child node
parentNode.appendChild(childNode);

// Insert before another node
parentNode.insertBefore(newNode, referenceNode);

// Remove child node
parentNode.removeChild(childNode);

// Replace child node
parentNode.replaceChild(newNode, oldNode);

// Clone node
let clone = node.cloneNode(true); // true = deep clone

Interactive Example:

Original paragraph

🔹 Node vs Element

Understanding the difference:

// childNodes includes ALL nodes (text, comments, elements)
let allNodes = element.childNodes;

// children includes only ELEMENT nodes
let elementNodes = element.children;

// Example: Count different node types
console.log('All nodes:', element.childNodes.length);
console.log('Element nodes only:', element.children.length);

Interactive Example:

Text 1 Text 2

🧠 Test Your Knowledge

What node type number represents an element node?