🌳 DOM Manipulation
The DOM (Document Object Model) is a programming interface for HTML documents. It represents the page as a tree of objects that JavaScript can interact with.
What is the DOM?
DOM Tree Structure
document
└── html
├── head
│ ├── title
│ └── meta
└── body
├── h1
├── p
└── div
├── span
└── button
Each HTML element becomes a node in the tree. JavaScript can:
- Select elements
- Change content
- Modify styles
- Add/remove elements
- Respond to events
Selecting Elements
getElementById
HTML
<div id="main">Content</div>
JavaScript
// Returns the element with id="main"
const element = document.getElementById('main');
console.log(element); // <div id="main">Content</div>
querySelector
// Selects first matching element (like CSS selector)
const element = document.querySelector('.classname');
const element = document.querySelector('#id');
const element = document.querySelector('div');
const element = document.querySelector('div.active');
const element = document.querySelector('[data-id="123"]');
querySelectorAll
// Returns ALL matching elements as a NodeList
const elements = document.querySelectorAll('.item');
// Loop through elements
elements.forEach(element => {
console.log(element);
});
💡 Best Practice
Use querySelector and querySelectorAll - they're more flexible
and use CSS selector syntax you already know!
Other Selection Methods
// Legacy methods (still useful)
document.getElementsByClassName('item'); // HTMLCollection (live)
document.getElementsByTagName('div'); // HTMLCollection (live)
Reading Content
const element = document.querySelector('#myDiv');
// Get text content (no HTML)
console.log(element.textContent);
// Get HTML content (including tags)
console.log(element.innerHTML);
// Get/set value of input
const input = document.querySelector('input');
console.log(input.value);
Changing Content
const element = document.querySelector('#myDiv');
// Change text (safe, escapes HTML)
element.textContent = 'New text';
// Change HTML (can insert HTML tags)
element.innerHTML = '<strong>Bold text</strong>';
// Change input value
const input = document.querySelector('input');
input.value = 'New value';
⚠️ Security Warning
Never use innerHTML with user input - it can execute scripts!
Use textContent instead.
Modifying Attributes
const img = document.querySelector('img');
// Get attribute
const src = img.getAttribute('src');
// Set attribute
img.setAttribute('src', 'new-image.jpg');
img.setAttribute('alt', 'New description');
// Remove attribute
img.removeAttribute('title');
// Check if attribute exists
if (img.hasAttribute('alt')) {
console.log('Has alt text');
}
// Direct property access (common attributes)
img.src = 'image.jpg';
img.alt = 'Description';
const link = document.querySelector('a');
link.href = 'https://example.com';
Modifying Styles
Inline Styles
const element = document.querySelector('.box');
// Set individual style properties
element.style.color = 'red';
element.style.backgroundColor = 'blue'; // Note: camelCase
element.style.fontSize = '20px';
element.style.border = '2px solid black';
// Set multiple styles
element.style.cssText = 'color: red; font-size: 20px; border: 2px solid black;';
CSS Classes (Better!)
const element = document.querySelector('.box');
// Add class
element.classList.add('active');
// Remove class
element.classList.remove('hidden');
// Toggle class (add if absent, remove if present)
element.classList.toggle('dark-mode');
// Check if class exists
if (element.classList.contains('active')) {
console.log('Element is active');
}
// Add multiple classes
element.classList.add('class1', 'class2', 'class3');
💡 Best Practice
Prefer using classList over inline styles. Define styles in CSS,
then add/remove classes with JavaScript. This keeps styling separate from logic.
Creating Elements
// Create element
const div = document.createElement('div');
// Add content
div.textContent = 'Hello, World!';
// Add classes/attributes
div.classList.add('box');
div.setAttribute('data-id', '123');
// Add to page
document.body.appendChild(div);
Adding/Removing Elements
appendChild
const parent = document.querySelector('.container');
const child = document.createElement('div');
// Add to end of parent
parent.appendChild(child);
insertBefore
const parent = document.querySelector('.container');
const newChild = document.createElement('div');
const existingChild = document.querySelector('.existing');
// Insert before existing child
parent.insertBefore(newChild, existingChild);
Modern Methods
const element = document.querySelector('.box');
const newElement = document.createElement('div');
// Insert at different positions
element.before(newElement); // Before element
element.after(newElement); // After element
element.prepend(newElement); // First child
element.append(newElement); // Last child
Removing Elements
const element = document.querySelector('.box');
// Modern way (remove itself)
element.remove();
// Old way (remove from parent)
const parent = element.parentElement;
parent.removeChild(element);
Traversing the DOM
const element = document.querySelector('.child');
// Parent
const parent = element.parentElement;
// Children
const children = parent.children; // HTMLCollection
const firstChild = parent.firstElementChild;
const lastChild = parent.lastElementChild;
// Siblings
const next = element.nextElementSibling;
const previous = element.previousElementSibling;
// Find closest ancestor matching selector
const container = element.closest('.container');
Practical Example
HTML
<ul id="todo-list"></ul>
<input type="text" id="todo-input">
<button id="add-btn">Add</button>
JavaScript
// Select elements
const todoList = document.querySelector('#todo-list');
const todoInput = document.querySelector('#todo-input');
const addBtn = document.querySelector('#add-btn');
// Add todo function
function addTodo() {
// Get input value
const text = todoInput.value.trim();
// Validate
if (text === '') return;
// Create new todo item
const li = document.createElement('li');
li.textContent = text;
// Add to list
todoList.appendChild(li);
// Clear input
todoInput.value = '';
}
// Listen for button click
addBtn.addEventListener('click', addTodo);
Summary
📚 What you learned
- DOM is a tree representation of HTML
- Select elements with
querySelector - Change content with
textContentorinnerHTML - Modify styles with
styleorclassList - Create elements with
createElement - Add elements with
appendChildorappend - Remove elements with
remove() - Traverse the DOM with parent/child/sibling properties