1. The DOM & Event Handling
Follow along with code examples here!
Table of Contents
Key Concepts
DOM (Document Object Model) — the tree-like structure of JavaScript objects that the browser creates when it loads an HTML page. It maps the hierarchical relationships between elements.
<script src="file.js">— links a JavaScript file to an HTML page. It should be placed at the end of the<body>to ensure all elements exist before the script runs.Event — a user interaction that the browser can detect, such as a click, mouse movement, key press, or form submission. Event Bubbling (Propagaion) — an event that occurs on an element can heard by all ancestors of that element.
Key Syntax
documentobject — the root object at the top of the DOM tree; our entry point for accessing and manipulating elements.document.querySelector(selector)— returns the first element matching the CSS selector (ornullif none).document.body— a shortcut reference to the<body>element.element.textContent— gets or sets the text content of an element (no HTML, just text).element.style.property— gets or sets an inline style on an element (e.g.element.style.backgroundColor = 'aqua').element.classList.add(className)— adds a CSS class to an element.element.classList.remove(className)— removes a CSS class from an element.element.classList.toggle(className)— adds the class if it’s missing, removes it if it’s present.element.remove()— removes the element from the DOM.element.addEventListener(eventType, handler)— registers an event handler function for a given event type on an element.eventobject — an object automatically passed to event handlers containing information about the event.event.target— the element that originally triggered the event.event.currentTarget— the element that is currently handling the event (the one the listener is attached to).event.type— the type of event that occurred (e.g.'click','keydown').event.key— for keyboard events, the actual key pressed (e.g.'a',' ').event.code— for keyboard events, the physical key on the keyboard (e.g.'Space','KeyA').
What Can JavaScript Do?
You've spent the last few weeks building beautiful, well-structured websites with HTML and CSS. But so far, your pages have been static—they look great, but they don't do anything when users interact with them.
JavaScript changes everything.
With JavaScript, you can make your pages respond to user actions:
Click a button → something happens
Type in a search box → results filter in real-time
Hover over an image → it zooms in
Submit a form → data gets saved
This is what we mean by interactive web applications. Let's see how it works.
In this lesson we'll first learn how to use JavaScript to manually manipulate HTML elements before learning how to make elements interactive.
The Document Object Model (DOM)
Consider this HTML structure:
When a browser loads an HTML page, it converts every single HTML element into a JavaScript object and organizes them into a structure called the Document Object Model (DOM). The DOM is a "tree-like" structure which maps the hierarchical relationship between elements.

The key insight: if elements are objects, we can modify and interact with them using JavaScript! We can change their text, their styles, their classes—anything.
The object at the top of this tree, document, is our entry point to interacting with these objects.
Selecting Elements with querySelector
TODO: Open the 0-balloon-pop/index.html file in your browser and open the Chrome DevTools. In the DevTools console, we can write JavaScript code that will interact directly with the DOM.
To grab a specific HTML element object from the DOM, we use the document.querySelector() method. It uses the same CSS selector syntax you already know:
Open your browser's DevTools (F12 or right-click → Inspect), go to the Console tab, and try selecting elements on any webpage using this method.
Once you have a reference to an element, you can read and modify its properties. You can even completely remove the element from the DOM:
Try these modifications one line at a time in your DevTools console!
Linking JavaScript to HTML
Using JavaScript in the DevTools console is great for testing. But every time we refresh the page, all of our work is lost and we have to write it again.
Instead, we can make a JavaScript file and have our HTML pages automatically run that file when the page loads.
For example, the 0-balloon-pop/index.js file contains the following code:
To run this file when our HTML page loads, add a <script src="index.js"> tag at the end of the body:
Now, when your browser loads this HTML page, it will automatically run the JavaScript file after the body content has loaded.
Q: Why does the <script> tag need to go at the end of the body?
JavaScript runs as soon as it loads. If your script tries to select an element that hasn't been added to the page yet, querySelector will return null and your code will break.
Try it out! The script will try to reference the balloon element before it exists.
By placing the <script> tag at the end of the body, you ensure all HTML elements have been loaded into the DOM before your JavaScript tries to access them.
Events
The most exciting part of making web applications is when we start adding interactivity by responding to events. An event is something that the user does on the page:
clicking on a button
hovering over an element
scrolling on the page
pressing a key on their keyboard
submitting a form.
Using JavaScript, we can decide how the page will react in response to these events occurring.
addEventListener: Listen and Handle
Adding interactivity requires telling our browser three things:
The element we want to be interactive
The event it will "listen" for
What to do to "handle" that event
We do this all with the with the addEventListener() method:
Let's break the addEventListener method down:
element— The HTML element that we want to be interactiveeventType— A string like'click','mouseover','keydown'handlerFunction— A callback that runs when the event "fires" (when it occurs)
Event Types and Handling Multiple Events
There are many event types you can listen for:
click
Element is clicked
dblclick
Element is double-clicked
mouseover
Mouse moves onto element
mouseout
Mouse leaves element
mousemove
Mouse moves while over element
keydown
A key is pressed
keyup
A key is released
submit
A form is submitted
input
An input's value changes
You can find a complete list of events on MDN.
A single element can even have multiple event listeners for different types of events:
Challenge: Add an event listener to the body that reacts whenever the mouse moves
The Event Object
When an event handler is called, it automatically receives an event object with information about what happened:
The two most important properties are:
event.type— The type of event that occurred ('click','keydown', etc.)event.target— The element that triggered the event.
The event object has a ton of information that is specific to each type of event. It can be useful to print out the entire event object to see what is available.
Q: Add the event parameter to the keydown listener and print it out. What properties tell us information about which key was pressed?
Answer
event.key(Recommended): Returns the string value of the character pressed, taking into account keyboard layout and modifier keys (e.g., "a", "A", "@").event.code: Identifies the physical key on the keyboard, regardless of language or modifier status (e.g., "KeyQ" for a QWERTY or AZERTY layout).
Tip: When trying a new event type, always log the event object to see what properties are available!
Event Bubbling (Propagation) and currentTarget
currentTargetTake another look at this event listener.
The body is the element that is listening for click events, right? Did you notice that you can click on elements inside the body rather than the body itself and the event handler will still fire. The value of event.target will tell us exactly which element you clicked on.
This is called event bubbling (a.k.a. event propagation) and it is a feature of the DOM whereby an event that occurs on an element can heard by all ancestors of that element.
If you ever need to distinguish the element that triggered the event from the element that is listening for the event, you can use event.currentTarget:
Challenge: Put It All Together
In 1-random-colors, open the index.html file
First, load the script file in index.js.
Inside of index.js is a function that generates a random RGB color string:
Your task is to do the following:
Add an event listener that changes the background color of the body whenever the "space" key is pressed
Add an event listener to the
+button that increases the font size of the"#instructions"section by1px.Add an event listener to the
-button that decreases the font size of the"#instructions"section by1px.
Last updated