The Document Object Model (DOM) is the browser's representation of your HTML page as a tree of objects. JavaScript can read and modify this tree, which is how you make web pages interactive.
Selecting Elements
getElementById
Select a single element by its id attribute:
const header = document.getElementById("main-header");
console.log(header.textContent);querySelector and querySelectorAll
Select elements using CSS selectors — the most versatile approach:
Comparison of Selection Methods
| Method | Returns | Use When |
|---|---|---|
getElementById | Element | You have a unique ID |
querySelector | Element | You need the first CSS match |
querySelectorAll | NodeList | You need all matching elements |
getElementsByClassName | HTMLCollection | Legacy code (prefer querySelector) |
Reading and Modifying Content
textContent vs innerHTML
<div id="output">
<strong>Hello</strong> World
</div>Always use textContent when inserting user-generated content to prevent cross-site scripting (XSS) attacks.
Modifying Styles and Classes
Working with Classes
Inline Styles
const box = document.querySelector(".box");
box.style.backgroundColor = "#E21B1B";
box.style.padding = "1rem";
box.style.display = "none";Prefer toggling CSS classes over setting inline styles — it keeps your JavaScript clean and your styles in CSS where they belong.
Modifying Attributes
Creating and Inserting Elements
createElement
Building Multiple Elements
Using a DocumentFragment is more efficient than appending elements one by one because it causes only a single reflow.
insertAdjacentHTML
A convenient way to insert HTML at specific positions:
Removing Elements
Event Handling
Events are how you respond to user interactions.
addEventListener
Common Events
| Event | Fires When |
|---|---|
click | Element is clicked |
input | Input value changes |
submit | Form is submitted |
keydown | Key is pressed |
mouseover | Cursor enters an element |
focus | Element gains focus |
blur | Element loses focus |
load | Page or resource finishes loading |
Event Delegation
Instead of adding listeners to many child elements, add one listener to a parent:
Event delegation is more memory-efficient and works for dynamically added elements.
Preventing Default Behavior
Practical Exercise
Build an interactive to-do list:
<input id="todo-input" type="text" placeholder="Add a task..." />
<button id="add-btn">Add</button>
<ul id="todo-list"></ul>Key Takeaways
- Use
querySelectorandquerySelectorAllfor selecting elements — they accept any CSS selector. - Prefer
textContentoverinnerHTMLwhen inserting user-generated content to prevent XSS. - Toggle CSS classes instead of setting inline styles for cleaner separation of concerns.
- Use
DocumentFragmentwhen inserting many elements to minimize reflows. - Event delegation on a parent element is more efficient than individual listeners on each child.