🎯 What You'll Learn
- What is the DOM (Document Object Model)?
- Selecting elements (querySelector, getElementById)
- Changing content and styles
- Creating and removing elements
- Working with classes and attributes
- Traversing the DOM (parent, child, sibling)
📚 Core Concepts
1. What is the DOM?
The DOM is a tree representation of your HTML page that JavaScript can interact with.
/* HTML becomes a tree of objects:
*
* document
* └─ html
* ├─ head
* │ └─ title
* └─ body
* ├─ h1
* └─ div
* └─ p
*/
// JavaScript can change any part of this tree!
console.log(document); // The entire page
2. Selecting Elements
// By ID (returns one element)
let title = document.getElementById('title');
// By class (returns collection)
let buttons = document.getElementsByClassName('btn');
// By tag name
let paragraphs = document.getElementsByTagName('p');
// Modern way: querySelector (CSS selectors!)
let firstBtn = document.querySelector('.btn'); // First match
let allBtns = document.querySelectorAll('.btn'); // All matches
// Complex selectors
let item = document.querySelector('#menu .item.active');
let inputs = document.querySelectorAll('input[type="text"]');
💡 Tip: querySelector is the most flexible! Use it for most cases.
3. Changing Content
let element = document.querySelector('#demo');
// Change text only
element.textContent = "New text";
// Change HTML (can include tags)
element.innerHTML = "Bold text";
// Get content
let text = element.textContent;
let html = element.innerHTML;
Original text
4. Changing Styles
let box = document.querySelector('.box');
// Change individual styles
box.style.color = 'red';
box.style.backgroundColor = 'yellow';
box.style.fontSize = '20px';
box.style.padding = '10px';
// Get computed styles
let styles = window.getComputedStyle(box);
let color = styles.color;
💡 Better Practice: Instead of inline styles, toggle CSS classes!
5. Working with Classes
let element = document.querySelector('.item');
// Add class
element.classList.add('active');
// Remove class
element.classList.remove('inactive');
// Toggle class (add if missing, remove if present)
element.classList.toggle('highlight');
// Check if has class
if (element.classList.contains('active')) {
console.log('Element is active!');
}
// Replace class
element.classList.replace('old-class', 'new-class');
6. Creating & Removing Elements
// Create new element
let newDiv = document.createElement('div');
newDiv.textContent = 'I am new!';
newDiv.classList.add('box');
// Add to page
let container = document.querySelector('#container');
container.appendChild(newDiv); // Add to end
container.insertBefore(newDiv, first); // Add before element
// Remove element
newDiv.remove(); // Modern way
// OR
container.removeChild(newDiv); // Old way
// Clone element
let copy = newDiv.cloneNode(true); // true = deep copy (with children)
7. Attributes
let link = document.querySelector('a');
// Get attribute
let url = link.getAttribute('href');
// Set attribute
link.setAttribute('href', 'https://example.com');
link.setAttribute('target', '_blank');
// Remove attribute
link.removeAttribute('target');
// Check if has attribute
if (link.hasAttribute('href')) {
console.log('Link has href');
}
// Direct property access (common attributes)
let img = document.querySelector('img');
img.src = 'photo.jpg';
img.alt = 'Description';
8. Traversing the DOM
let element = document.querySelector('.item');
// Parents
let parent = element.parentElement;
let ancestor = element.closest('.container'); // Find nearest ancestor
// Children
let firstChild = parent.firstElementChild;
let lastChild = parent.lastElementChild;
let allChildren = parent.children; // HTMLCollection
// Siblings
let nextSib = element.nextElementSibling;
let prevSib = element.previousElementSibling;
🛠️ Practice Projects
Project 1: Color Changer
Change background color by clicking buttons
Features to add:
- 3-5 buttons for different colors
- Click button to change page background
- Show current color name on screen
- Add a "random color" button
Project 2: Interactive To-Do List
Add, remove, and mark tasks as complete
Features to add:
- Input field to add new todos
- Click todo to mark complete (strikethrough)
- Delete button for each todo
- Counter showing total todos
- Clear all completed button
Project 3: Image Gallery
Click thumbnails to show larger version
Features to add:
- Grid of thumbnail images
- Click to display in larger view
- Show image title/description
- Previous/Next buttons
- Close button to exit