Introduction
The Document Object Model (DOM) is a programming interface for HTML documents. It represents the page structure as a tree of objects that JavaScript can manipulate. In this lesson, you'll learn how to select elements, modify content, handle events, and create interactive web experiences.
Learning Objectives
By the end of this lesson, you will be able to:
- Select and manipulate DOM elements using modern methods
- Handle user events like clicks, inputs, and form submissions
- Create, modify, and remove elements dynamically
- Understand event bubbling and delegation
- Build interactive user interfaces
- Apply best practices for DOM manipulation
Prerequisites
- Completion of Lessons 01-02
- Understanding of HTML structure
- Basic CSS knowledge
- Familiarity with functions and callbacks
Estimated Time
4 hours (including practice exercises)
Selecting Elements
// Select by ID
const header = document.getElementById('header');
// Select by class (returns first match)
const button = document.querySelector('.btn');
// Select all matching elements
const allButtons = document.querySelectorAll('.btn');
// Select by tag name
const paragraphs = document.getElementsByTagName('p');
Modifying Content
// Change text content
element.textContent = 'New text';
// Change HTML content
element.innerHTML = 'Bold text';
// Modify attributes
element.setAttribute('class', 'active');
element.classList.add('highlight');
element.classList.remove('hidden');
element.classList.toggle('active');
Event Handling
// Click event
button.addEventListener('click', (event) => {
console.log('Button clicked!');
});
// Form submission
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(event.target);
console.log(Object.fromEntries(formData));
});
// Input change
input.addEventListener('input', (event) => {
console.log(event.target.value);
});
Key Takeaways
- Use querySelector and querySelectorAll for flexible element selection
- Modify content with textContent and innerHTML
- Use classList methods to manage CSS classes
- addEventListener provides powerful event handling
- Always use event.preventDefault() to stop default form behavior
Practice Exercises
Exercise 1: Interactive Counter
Create a counter with increment, decrement, and reset buttons:
<div id="counter">
<h2>Count: <span id="count">0</span></h2>
<button id="increment">+</button>
<button id="decrement">-</button>
<button id="reset">Reset</button>
</div>
// Add event listeners to make the counter work
// Hint: Select elements and update the count span
Exercise 2: Todo List
Build a simple todo list with add and remove functionality:
// Create a todo list that:
// 1. Adds new items when form is submitted
// 2. Removes items when delete button is clicked
// 3. Marks items as complete when clicked
// 4. Shows the total number of todos
Exercise 3: Form Validation
Validate a registration form before submission:
// Validate a form with:
// - Email (must contain @)
// - Password (minimum 8 characters)
// - Confirm password (must match password)
// Show error messages for invalid fields
Exercise 4: Image Gallery
Create an interactive image gallery with thumbnails:
// Build a gallery that:
// 1. Shows a main large image
// 2. Displays thumbnail images below
// 3. Changes main image when thumbnail is clicked
// 4. Adds 'active' class to current thumbnail
Best Practices
- Cache DOM queries - store element references in variables instead of querying repeatedly
- Use event delegation for dynamically added elements
- Prefer textContent over innerHTML when not inserting HTML
- Always validate and sanitize user input
- Use semantic HTML and ARIA attributes for accessibility
- Debounce expensive operations like search or scroll handlers
Additional Resources
What's Next?
Lesson 04 will introduce asynchronous JavaScript, teaching you how to handle operations that take time, like fetching data from APIs or reading files. You'll master Promises and async/await syntax.