3. Modern JavaScript Fundamentals
DOM Manipulation, Events & Dynamic UI
Connect JavaScript to HTML elements: master the DOM tree, querySelector, safe textContent updates, classList, createElement, addEventListener, and event delegation.
- Select single and multiple HTML elements using querySelector and querySelectorAll
- Update text, classes, and dynamic DOM nodes safely without XSS vulnerabilities
- Respond cleanly to clicks, typing, and form submissions using addEventListener
When a browser finishes reading your HTML file, it converts every tag into a live, structured tree of JavaScript objects in memory called the DOM (Document Object Model). Because the DOM is live, whenever your JavaScript updates a node in the DOM, the pixels on the user's screen update instantaneously—without refreshing the page.
Selecting Elements (querySelector & querySelectorAll)
Think of document as the root handle to the whole webpage. You pass standard CSS selectors (#id, .class, tag) into two core selector methods:
// Grab the FIRST matching element (returns null if not found)
const titleEl = document.querySelector("#lesson-title");
const primaryBtn = document.querySelector(".complete-btn");
// Grab ALL matching elements as a list you can loop over
const cards = document.querySelectorAll(".course-card");
cards.forEach((card) => console.log(card.textContent));If you put <script src="app.js"></script> inside <head>, add the defer keyword (<script src="app.js" defer></script>). That guarantees the browser finishes parsing all HTML elements before your querySelector() calls run, preventing frustrating "Cannot read properties of null" errors!
Updating Text, Styles & Classes Safely
Once you hold a DOM element reference, three operations cover almost every visual state update:
- Update plain text (
textContent): Always preferelement.textContent = userInputoverinnerHTML! SettinginnerHTMLwith user-supplied text lets attackers inject malicious<script>tags (Cross-Site Scripting / XSS), whereastextContentrenders characters safely as literal text. - Toggle visual state (
classList): Keep visual styles inside CSS classes (.done,.open,.hidden) and toggle them cleanly from JavaScript:
const badge = document.querySelector("#status-badge");
badge.textContent = "Completed";
badge.classList.add("done");
badge.classList.toggle("highlighted");- Build new elements (
createElement): Construct list items safely without string HTML concatenation:
const li = document.createElement("li");
li.textContent = "Finish DOM lesson";
document.querySelector("#task-list").append(li);Listening to User Actions (addEventListener)
Instead of scattering ugly onclick="..." attributes inside HTML, keep behavior cleanly inside JavaScript with addEventListener(eventType, callback):
| Event Name | When It Fires | Typical Action |
|---|---|---|
"click" | User clicks button/link or triggers via Enter | Toggle menus, increment counters, open dialogs |
"input" | Fires on every keystroke inside an <input> | Live search filtering or character counters |
"submit" | User submits a <form> (button click or Enter key) | Call event.preventDefault(), validate inputs, save data |
Notice what event.preventDefault() does inside a form "submit" handler: by default, HTML forms reload the entire browser page when submitted. Calling event.preventDefault() cancels that page reload so your JavaScript updates the DOM smoothly on the spot!
Try It Live: Dynamic Task List with Input & Events
Type a topic into the preview input below and click Add Note (or press Enter)—watch createElement, textContent, preventDefault(), and classList working together live:
Quick Checkpoints
Why do we call event.preventDefault() inside a form submit event listener?
Which DOM property is safest when displaying text typed by a user onto the screen?