What is the DOM
The Document Object Model (DOM) is a programming interface for HTML documents. It represents the page as a tree of objects that JavaScript can manipulate.
DOM as a Tree
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello</h1>
<p>World</p>
</body>
</html>
DOM Tree:
Document
└─ html
├─ head
│ └─ title
│ └─ "My Page"
└─ body
├─ h1
│ └─ "Hello"
└─ p
└─ "World"
DOM vs HTML Source
// HTML source is just text
// DOM is a live, interactive representation
// The DOM is always current
// HTML source doesn't change when JS modifies the page
console.log(document.body.innerHTML); // Current DOM state
console.log(document.documentElement.outerHTML); // Full DOM
Why DOM Matters
// Without DOM: static HTML only
// With DOM: dynamic, interactive pages
document.querySelector('h1').textContent = 'New Title';
document.body.style.backgroundColor = 'blue';
DOM is a Web API
// DOM is provided by the browser, not JavaScript itself
// It's part of the Web API (like fetch, setTimeout, etc.)
// JavaScript can:
// - Read from the DOM
// - Modify the DOM
// - Add/remove elements
// - Listen to DOM events
DOM Tree Structure
The DOM is organized as a tree with different node types.
Node Types
// Element nodes (HTML tags)
const div = document.createElement('div');
// Text nodes
const text = document.createTextNode('Hello');
// Comment nodes
const comment = document.createComment('TODO');
// Document node
console.log(document.nodeType); // 9
console.log(document.nodeName); // '#document'
Node Relationships
<div id="parent">
<p id="child1">First</p>
<p id="child2">Second</p>
</div>
const parent = document.getElementById('parent');
const child1 = document.getElementById('child1');
const child2 = document.getElementById('child2');
// Parent
console.log(child1.parentNode); // div#parent
console.log(child1.parentElement); // div#parent
// Children
console.log(parent.children); // HTMLCollection [p, p]
console.log(parent.childNodes); // NodeList [text, p, text, p, text]
// Siblings
console.log(child1.nextElementSibling); // p#child2
console.log(child1.nextSibling); // text (whitespace)
console.log(child2.previousElementSibling); // p#child1
Node vs Element
// childNodes includes ALL node types (text, comment, etc.)
console.log(parent.childNodes.length); // 5 (including whitespace)
// children includes only Element nodes
console.log(parent.children.length); // 2
// firstChild vs firstElementChild
console.log(parent.firstChild); // text node (whitespace)
console.log(parent.firstElementChild); // p#child1
DOM APIs
The DOM provides many APIs for interacting with the document.
Core APIs
// Document
const title = document.title;
const body = document.body;
const head = document.head;
// Window
const width = window.innerWidth;
const height = window.innerHeight;
// Location
const url = window.location.href;
const path = window.location.pathname;
Selection APIs
// By ID
const element = document.getElementById('myId');
// By class
const items = document.getElementsByClassName('item');
// By tag
const divs = document.getElementsByTagName('div');
// CSS selector (modern)
const el = document.querySelector('.myClass');
const all = document.querySelectorAll('div > p');
Manipulation APIs
// Content
element.textContent = 'New text';
element.innerHTML = '<b>Bold</b>';
// Attributes
element.setAttribute('class', 'active');
element.getAttribute('id');
element.removeAttribute('disabled');
// Styles
element.style.color = 'red';
element.style.cssText = 'color: red; font-size: 16px;';
// Classes
element.classList.add('active');
element.classList.remove('hidden');
element.classList.toggle('visible');
Creation APIs
// Create elements
const div = document.createElement('div');
const text = document.createTextNode('Hello');
// Add to DOM
document.body.appendChild(div);
parent.insertBefore(newChild, referenceChild);
// Remove from DOM
parent.removeChild(child);
child.remove(); // Modern
Event APIs
// Add listener
element.addEventListener('click', handler);
// Remove listener
element.removeEventListener('click', handler);
// Event object
function handler(event) {
console.log(event.type); // 'click'
console.log(event.target); // clicked element
console.log(event.currentTarget); // element with listener
}
Practice Problems
Create a reusable React component implementing DOM. 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 using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize DOM 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's the difference between childNodes and children?
3. Which API selects the first matching element?
4. Is the DOM part of JavaScript or the browser?
Flashcards
Question
What is the DOM?
Click to reveal answer
Answer
A tree of objects representing an HTML document. JavaScript uses the DOM API to read and manipulate the page.
Question
What is the difference between childNodes and children?
Click to reveal answer
Answer
childNodes includes all node types (text, comment, element). children includes only Element nodes.
Question
What does querySelector return?
Click to reveal answer
Answer
The first element matching a CSS selector. Returns null if no match.
Question
Is the DOM part of JavaScript?
Click to reveal answer
Answer
No, the DOM is a Web API provided by the browser. JavaScript accesses it through the browser's API.
Question
What is DOM?
Click to reveal answer
Answer
DOM is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.The DOM is a tree of objects representing HTML
- 2.JavaScript manipulates pages through the DOM API
- 3.childNodes vs children: all nodes vs elements only
- 4.querySelector is the most versatile selection method
- 5.The DOM is a Web API, not part of JavaScript itself
Interview Tips
- •Explain the DOM tree structure with an example
- •Show the difference between childNodes and children
- •Demonstrate DOM selection methods
- •Discuss DOM manipulation performance considerations
Cheat Sheet
DOM Cheat Sheet
What is it?
Tree of objects representing an HTML document.
Node Types
- Element (tags)
- Text (content)
- Comment
- Document
Key APIs
- Selection: getElementById, querySelector, querySelectorAll
- Traversal: parentNode, children, siblings
- Manipulation: textContent, innerHTML, style, classList
- Creation: createElement, appendChild, remove
- Events: addEventListener, removeEventListener
Node vs Element
- childNodes: all nodes (text, comment, element)
- children: only element nodes