← Back to Week 5
Feb 2, 2026
DOM Manipulation & Events
Lecture Notes
Slides: The DOM
The Document Object Model (DOM)
- The DOM is a tree of element nodes representing HTML structure
- JavaScript can access and manipulate this tree programmatically
- The
document object is the entry point to the DOM
Selecting Elements
document.querySelector(selector) — returns first matching element
document.querySelectorAll(selector) — returns NodeList of all matches
- Use any CSS selector:
'#id', '.class', 'tag', 'div > p'
Modifying Content
element.textContent — get/set text content (no HTML parsing)
element.innerHTML — get/set HTML content (parses HTML tags)
Changing Attributes & Styles
- Attributes:
element.src, element.href, element.alt
- Classes:
classList.add('class'), classList.remove('class'), classList.toggle('class')
- Inline styles:
element.style.fontSize = '2rem' (camelCase property names)
Creating Elements
document.createElement('tag') — creates a new element
parent.appendChild(element) — adds element as last child
- Set properties before appending:
newDiv.textContent = 'Hello'
Render Functions
- Create functions like
renderCard(data) that build and return DOM elements
- Keeps code organized and reusable
- Pattern: create element → set properties → append children → return element
Event Handling
element.addEventListener('event', callback) — registers an event handler
- Common events:
'click', 'submit', 'input', 'change'
- Callback receives an
event object with details about the event
event.preventDefault() — stops default browser behavior (e.g., form submission)
Web App Architecture
- Define application state (data) as variables
- Create render functions to display state
- On user actions, update state then re-render
Form Handling
- Listen for
'submit' event on the form element
- Call
event.preventDefault() to stop page reload
- Access input values via
inputElement.value
Key Concepts
- DOM: Tree representation of HTML that JavaScript can manipulate
- querySelector: Select elements using CSS selectors
- textContent vs innerHTML: Plain text vs HTML parsing
- classList: Add, remove, or toggle CSS classes
- createElement: Dynamically build new DOM elements
- addEventListener: Respond to user interactions
- preventDefault: Stop default browser behavior