HTML to DOM
When a browser receives HTML, it converts it into a Document Object Model (DOM) - a tree structure that JavaScript can interact with.
Parsing Process
HTML Document
↓
Tokenizer (breaks into tokens)
↓
Tree Builder (creates node tree)
↓
DOM Tree
↓
Render Tree (with CSS)
↓
Layout → Paint → Display
HTML → DOM Example
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<h1>Hello</h1>
<p>World</p>
</body>
</html>
DOM Tree:
Document
└── html
├── head
│ └── title
│ └── "Page"
└── body
├── h1
│ └── "Hello"
└── p
└── "World"
Why DOM Matters
- JavaScript access: DOM is the API for manipulating pages
- Dynamic content: Add, remove, modify elements
- Event handling: Respond to user interactions
- Performance: Understanding DOM helps write efficient code
Browser DOM API
// Access the document
console.log(document); // Document node
console.log(document.documentElement); // <html>
console.log(document.body); // <body>
console.log(document.head); // <head>
// Get elements
const h1 = document.querySelector('h1');
const paragraphs = document.querySelectorAll('p');
// Check node type
console.log(h1.nodeType); // 1 (Element node)
console.log(h1.nodeName); // "H1"
console.log(h1.nodeValue); // null (elements have no value)
Text Nodes
<p>Hello <strong>World</strong></p>
p
├── "Hello " (text node)
└── strong
└── "World" (text node)
Note: "Hello " includes the space!
const p = document.querySelector('p');
console.log(p.childNodes.length); // 3 (text, element, text)
console.log(p.childNodes[0].nodeType); // 3 (Text node)
console.log(p.childNodes[0].nodeValue); // "Hello "
DOM Tree
The DOM is a tree of nodes with specific relationships and hierarchy.
Node Relationships
<div id="parent">
<p id="child1">First</p>
<p id="child2">Second</p>
<p id="child3">Third</p>
</div>
Parent-Child Relationships:
parent
├── child1 (first child)
├── child2 (next sibling of child1)
└── child3 (next sibling of child2, last child)
Navigation:
parent.firstChild → child1
parent.lastChild → child3
child1.nextSibling → child2
child2.previousSibling → child1
child3.parentNode → parent
Node Types
| Type | Name | nodeType | Example |
|---|---|---|---|
| 1 | Element | 1 | <div>, <p> |
| 2 | Attribute | 2 | id="main" |
| 3 | Text | 3 | "Hello World" |
| 8 | Comment | 8 | <!-- comment --> |
| 9 | Document | 9 | document |
| 11 | DocumentFragment | 11 | Temporary container |
Traversing the DOM
const parent = document.getElementById('parent');
// Children
parent.children; // HTMLCollection of elements
parent.childNodes; // NodeList of all nodes
parent.firstElementChild; // First element child
parent.lastElementChild; // Last element child
// Siblings
const child2 = document.getElementById('child2');
child2.nextElementSibling; // child3
child2.previousElementSibling; // child1
// Parent
child2.parentElement; // div#parent
child2.parentNode; // div#parent
child2.closest('div'); // div#parent
Modifying the DOM
// Create elements
const div = document.createElement('div');
const text = document.createTextNode('Hello');
// Add content
div.textContent = 'Hello';
div.innerHTML = '<strong>Hello</strong>';
// Add to DOM
parent.appendChild(div); // Add at end
parent.prepend(div); // Add at start
parent.insertBefore(div, child1); // Before child1
// Remove from DOM
parent.removeChild(div);
div.remove(); // Modern way
// Replace
parent.replaceChild(newChild, oldChild);
// Clone
const clone = div.cloneNode(true); // Deep clone
Performance Tips
// ❌ Bad: Multiple DOM reads/writes
for (let i = 0; i < 100; i++) {
document.body.innerHTML += '<p>Item ' + i + '</p>'; // Reflow each time!
}
// ✅ Good: Build string, then insert
let html = '';
for (let i = 0; i < 100; i++) {
html += '<p>Item ' + i + '</p>';
}
document.body.innerHTML = html; // Single reflow
// ✅ Better: Use DocumentFragment
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const p = document.createElement('p');
p.textContent = 'Item ' + i;
fragment.appendChild(p);
}
document.body.appendChild(fragment); // Single reflow
DOM Node Types
Understanding node types helps you work with the DOM effectively.
Node Type Constants
const nodeTypes = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11
};
// Check node type
const element = document.querySelector('div');
console.log(element.nodeType); // 1
console.log(element.nodeName); // "DIV"
const text = document.createTextNode('Hello');
console.log(text.nodeType); // 3
console.log(text.nodeName); // "#text"
Element Nodes
const div = document.querySelector('div');
div.tagName; // "DIV" (uppercase)
div.nodeName; // "DIV" (uppercase)
div.localName; // "div" (lowercase)
div.id; // "myId"
div.className; // "class1 class2"
div.classList; // DOMTokenList
div.dataset; // {key: value} (data attributes)
Text Nodes
const p = document.querySelector('p');
// Get text content
p.textContent; // All text (including hidden)
p.innerText; // Visible text (respects CSS)
p.innerHTML; // HTML content
// Modify text
p.textContent = 'New text';
p.innerHTML = '<strong>Bold</strong>';
// Text node manipulation
const textNode = document.createTextNode('Hello');
p.appendChild(textNode);
Attribute Nodes
const div = document.querySelector('div');
// Get attributes
div.getAttribute('id');
div.getAttribute('class');
div.hasAttribute('data-value');
// Set attributes
div.setAttribute('id', 'newId');
div.setAttribute('data-value', '123');
// Remove attributes
div.removeAttribute('class');
// Attributes collection
const attrs = div.attributes;
for (let i = 0; i < attrs.length; i++) {
console.log(attrs[i].name, attrs[i].value);
}
DocumentFragment
// Create a container for batch operations
const fragment = document.createDocumentFragment();
// Add elements to fragment (no DOM reflow)
for (let i = 0; i < 100; i++) {
const li = document.createElement('li');
li.textContent = 'Item ' + i;
fragment.appendChild(li);
}
// Single DOM update
document.querySelector('ul').appendChild(fragment);
// Fragment is empty after appending
console.log(fragment.childNodes.length); // 0
Practice Problems
Create a reusable React component implementing DOM Structure. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for DOM Structure using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize DOM Structure for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is the DOM?
2. What is the nodeType of an element node?
3. What is the difference between textContent and innerHTML?
4. What is a DocumentFragment?
Flashcards
Question
What is the DOM?
Click to reveal answer
Answer
Document Object Model - a tree structure representing HTML that JavaScript can interact with to manipulate pages.
Question
What are the main node types?
Click to reveal answer
Answer
Element (1), Attribute (2), Text (3), Comment (8), Document (9), DocumentFragment (11).
Question
What is the difference between childNodes and children?
Click to reveal answer
Answer
childNodes includes all nodes (elements, text, comments). children includes only element nodes.
Question
Why use DocumentFragment?
Click to reveal answer
Answer
To batch DOM operations and minimize reflows. Build the tree offline, then insert with a single DOM update.
Question
What is DOM Structure?
Click to reveal answer
Answer
DOM Structure is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.The DOM is a tree structure that represents the HTML document
- 2.Different node types have different properties and uses
- 3.Use childNodes for all nodes, children for elements only
- 4.DocumentFragment helps minimize DOM reflows
- 5.Understanding DOM performance is key to efficient code
Interview Tips
- •Explain what the DOM is and how it's created
- •Know the difference between textContent, innerHTML, and innerText
- •Understand node traversal (parent, child, sibling)
- •Know how to efficiently manipulate the DOM
Cheat Sheet
DOM Structure Cheat Sheet
What is DOM:
- Tree representation of HTML
- JavaScript API for page manipulation
- Created by browser parser
Node Types:
- Element (1): ,
- Text (3): "Hello World"
- Comment (8):
- Document (9): document object
Navigation:
- parentNode / parentElement
- childNodes / children
- firstChild / firstElementChild
- lastChild / lastElementChild
- nextSibling / nextElementSibling
- previousSibling / previousElementSibling
Modification:
- createElement()
- appendChild() / prepend()
- removeChild() / remove()
- replaceChild()
- cloneNode()
Performance:
- Minimize DOM operations
- Use DocumentFragment
- Batch reads and writes