What is the DOM?
The DOM (Document Object Model) is the browser’s representation of your HTML as JavaScript objects. Every HTML tag is a “node” that you can manipulate: change text, styles, add events, etc.Selecting Elements
querySelector
Finds one element using CSS selectors:getElementById
Finds an element by ID (faster than querySelector for IDs):querySelectorAll
Finds all matching elements:The Type Problem
querySelector returns a very generic type:
Solution: Generic Helper Function
From our project, we created a reusable helper:main.ts
Using the Generic Helper
Common HTML Element Types
| Element | TypeScript Type |
|---|---|
<button> | HTMLButtonElement |
<input> | HTMLInputElement |
<div> | HTMLDivElement |
<a> | HTMLAnchorElement |
<img> | HTMLImageElement |
<form> | HTMLFormElement |
<select> | HTMLSelectElement |
| Any element | HTMLElement |
Generics Explained: <T>
Changing Element Content
textContent
Set plain text (safer - escapes HTML):innerHTML
Set HTML content:main.ts
Changing Element Attributes
Direct Property Access
setAttribute
Data Attributes (dataset)
main.ts
Hiding/Showing Elements
main.ts
Event Listeners
Basic Click Event
main.ts
Event with Type
Common Events
| Event | Trigger |
|---|---|
click | Element clicked |
submit | Form submitted |
input | Input value changed |
change | Select/checkbox changed |
keydown | Key pressed |
mouseover | Mouse enters element |
focus | Element receives focus |
Event Delegation
Instead of adding listeners to many elements, add ONE to the parent:main.ts
Why Event Delegation?
- One listener instead of 100
- Works with dynamically added elements
- Better performance
Creating Elements Dynamically
main.ts
Template Literals for HTML
Create HTML strings with variables:main.ts
Rendering Arrays with map() and join()
main.ts
DOM Manipulation Flow
- Select element
- Check if exists (or use our helper that throws)
- Modify content/attributes/styles
- Listen to events if needed
Next Steps
- Fetch API - Load data to display in DOM
- Async/Await - Handle async operations
- Interfaces - Type your data structures