Here is a sample CodeSandbox for you to fork and use throughout the lesson → Lesson 12 CodeSandbox Starter: The DOM
Warm-Up
Check out the homepage of the Kode with Klossy website: https://www.kodewithklossy.com/
- What HTML elements and CSS properties that we’ve learned about likely control the page’s layout and design?
- Where do you notice interactive elements on the homepage?
In this lesson, we’re going to learn how to incorporate interactivity through JavaScript, powering features like those on the KWK website!
What is the DOM?
The DOM, or Document Object Model, represents how the browser reads HTML. It allows JavaScript to interact with your HTML, which ultimately lets us manipulate, structure, and style our websites. Manipulating the DOM refers to changes that are made in the browser, which are prompted but not directly created by the user.
Here's a real-life example of DOM Manipulation:
If I type my email in a form, then click "Submit," I might see a message like "Thanks for signing up!"
I clicked the button, and in response, JavaScript made that message appear. In this lesson, we will learn how to change something on our site based on user interaction.
The DOM Tree
The DOM represents the HTML document as a tree structure where each node is an object representing a part of the document. This tree-like structure is often called the DOM tree.
Still confused about the DOM? It’s a common stumbling block! Many people struggle to see where the HTML ends and the DOM begins. Watch this video to see how the browser parses your static code and converts it into a live, interactive model that JavaScript can manipulate in real-time.

Document └── HTML ├── Head │ ├── Title │ └── Meta └── Body ├── Header │ └── H1 ├── Main │ ├── Section │ │ ├── H2 │ │ └── P │ └── Section │ ├── H2 │ └── P └── Footer └── P
Access Elements from the DOM
Accessing elements is the first step in building out the functionality to respond to user input. When we say "accessing elements", we mean being able to refer to specific parts of a webpage, like a button, a heading, or a paragraph, so that we can read their content or change them with code. This is the bridge that allows our HTML, CSS, and JavaScript to communicate! Once you access an element, you can update its text, change its style, or respond to user actions like clicks or hovers. By the end of this lesson, you'll be able to let a user click a button and see something happen on the screen in response.
JavaScript has built-in methods that allow us to access elements from the DOM. Here are some common ways to access elements:
querySelector
const header = document.querySelector('#main-header'); // Get element by ID const firstParagraph = document.querySelector('.content'); // Get element by class const firstLink = document.querySelector('a'); // Get element by tag
Of these three ways to access elements,
querySelector is our Swiss Army knife. It can find elements by ID, class, or even tag name using CSS selectors! An important distinction is that querySelector only returns the first element it finds that matches your criteria! If you have three paragraphs with the content class, querySelector(".content") will only return the first one, not all three.Try-It | Access DOM Elements
The first step in DOM manipulation is "grabbing" the element you want to change and giving it a name (a variable). In your JavaScript file, access the following elements and store them in variables using
const. Then, use console.log() to print those variables to the console so you can see what the browser "sees."- By ID: Access the h1 with the
main-headerID.
- By Class: Access the Travel Facts header with the
fact-headerclass.
- By Tag: Access the first
h2on the page with the element tag.
const mainTitle = document.querySelector('.first-fact'); console.log(mainTitle);
When you save your work or refresh the preview, check the console in CodeSandbox! You shouldn’t just see text—you should see the entire HTML tag (e.g.,
<li class="first-fact">...</li>).🌶🌶 Medium Challenge: Read the MDN documentation for
document.querySelectorAll. Try using this method to grab all of the facts instead of only the first one. How is the console output for querySelectorAll different from querySelector? When might you use this new method?Changing Content on the DOM
Now that we can access elements and store them in a variable, the possibilities are endless! Let's start by programmatically changing the content of an element. We can use
.textContent or .innerHTML to change the text inside of an element.const header = document.getElementById('main-header'); header.textContent = "HIIII"; // In the browser, the h1 now says HIIII // Or using innerHTMLheader.innerHTML = "HIIII";
What's happening? We're accessing the
h1 element and changing its text content. Whatever string is assigned to .textContent or .innerHTML will replace the text inside of the h1.Changing DOM content is like editing a sign:
- Using
textContentis like erasing the sign and writing plain text on it—simple but limited.
- Using
innerHTMLis like being able to not just write text, but also add images, change colors, or make some words bold —more powerful, but also more complex.
Try-It | Change DOM Content
A travel guide needs to be up-to-date! By only adding code to the JavaScript file, change the text inside of at least two elements. For example, change the
#main-header to a different city or update a fact in the list.🌶🌶 Medium Challenge: Select your
h1 element. On one line, use textContent to change it to “Destination: Mars”. On the very next line, use textContext to change it to “Destination: Hawaii”. Refresh your page. Which destination do you see on the screen? Why do you think that is?Changing CSS with JavaScript
One cool thing about JavaScript is that since it's accessing your HTML elements, you can also access the styles that have been applied to each element! Every element we access in the DOM has a .style property. This property acts like a bridge to your CSS file, allowing you to modify styles directly through JavaScript. However, there is one major rule to remember: JavaScript doesn't like dashes.
- In CSS, we use "kebab-case" (dashes):
background-color,font-size,border-radius.
- In JavaScript, we use "camelCase":
backgroundColor,fontSize,borderRadius.
How it looks in code:
const header = document.getElementById('main-header'); header.style.color = 'indigo'; header.style.fontSize = '50px';
This code follows a simple "Select and Apply" pattern: first, it locates the specific HTML element using its unique ID. Then, it uses the
.style property to reach into the element's CSS and reassign values for its color and size.Try-It | Change CSS with JavaScript
Let’s practice selecting elements and customizing the styles on the page without touching the CSS file! Modify your JavaScript file to give the
.calculator section a new background color and rounded corners.🌶🌶 Medium Challenge: In the real world, we use JavaScript to change styles only when certain conditions are met. For example, if a flight is sold out, we might want to "gray out" a button and make it unclickable. Create a variable called
isSoldOut and set it to true. Write an if statement to change the "Book Flight" button's backgroundColor to "gray" and change the cursor to "not-allowed" when isSoldOut is true.Functions and the DOM Together: Events
Events are really at the core of DOM Manipulation. When we talked about user interaction earlier, that's exactly what we mean. An event is any action that the user takes while on our site. Clicking a button, scrolling down, hovering over something, and more.
Event Listeners
Imagine that you've just ordered food for delivery and are waiting for it to arrive. When the doorbell rings, you'll stand up from the couch, walk over to the door, open it, and take your food. Guess what? You programmed yourself with an event listener.
In order for our site to respond to events, we need to write some code so that our site becomes "smart" enough to look out for a specific event on a specific element. This "look out" is called an event listener. Their job is to sit around and wait for an event to take place in the browser, and call a function for us when it does.
const button = document.querySelector('button'); button.addEventListener("click", doSomething); function doSomething() { alert("You clicked the button!"); };
An event listener is like installing a doorbell system:
- The doorbell button (the element) is connected to a listening device inside your house (the event listener).
- When someone presses the button (the event), the listening device hears it and triggers the chime (the handler function).
- You can set up different responses for different doorbells (multiple event listeners), and you can change what happens when the doorbell rings without having to replace the entire system.
Real World: JavaScript: ----------- ----------- 1. Install doorbell 1. Select element 2. Connect to chime 2. Add event listener 3. Wait for someone to press it 3. Browser waits for event 4. When pressed, chime rings 4. When event occurs, function runs
const button = document.getElementById("doorbell"); button.addEventListener("click", ringChime); function ringChime() { alert("Ding dong!"); }
Event Handlers
The event listener is responsible for monitoring an element for an event and doing something when the event occurs. The event handler is the function that's called when the event occurs. In our previous example, the function
doSomething was our event handler.Try-It | Event Listeners & Handlers
Now that we can access elements and change their text, we need to make those changes happen in response to the user. This is called Event Handling. Let’s make the “Book Flight” section work. Add a click event listener to the “Book Flight” button. Update the JavaScript so that when the button is clicked, the
#status-text changes to show the user that their action was successful.- Access the “Book Flight” button (
#toggle-button) and store it in a variable.
- Access the status text (
#status-text) and store it in a variable.
- Add an Event Listener to the button that listens for a
'click'.
- Write an Event Handler (function) that changes the booking status text from “NOT STARTED” to “CONFIRMED! ✈️”.
🌶 Mild Challenge: Use an event listener and an event handler to update the
#info-paragraph with the current weather when the user clicks the “Check Weather” button.By now, you’ve seen how the Document Object Model (DOM) acts as the bridge between your static HTML and the dynamic power of JavaScript. You’ve learned how to select specific elements on a page, modify their text or appearance using properties like
.textContent and .style, and most importantly, how to use Event Listeners to wait for user interaction. As you move into the practice, remember that you are essentially "wiring" the page: you'll identify the part of the travel app you want to control and then tell JavaScript exactly which function to trigger when a traveler clicks a button.Practice | Functions: Building Your Own Calculator
Add event listeners to the calculator so that a user can calculate their travel costs. We’ve provided the first event handler function (
addCosts) in your JavaScript file. Before you dive in, let’s take a closer look at two important tools in the addCosts function:.value: This "reaches" into the input box to grab exactly what the user typed. Without it, you’d just be grabbing the empty box itself!
Number(): By default, computers see text in a box as a "String" ("10").Number()converts that text into a number so the calculator can actually do math!
Follow these steps in order to build your travel calculator:
- In your JavaScript file, create an
addBtnvariable for the#add-buttonand aresultvariable for the#resultparagraph.
- Add a
'click'event listener to the “Add” button and pass theaddCostsfunction as the second parameter for the event listener.
- Test it! Enter two numbers and click the “Add” button. If the “Total Cost” updates, repeat these steps for the “Subtract”, “Multiply”, and “Divide” buttons!
🌶 Mild Challenge: Make sure the “Clear” button resets the input fields and the result.
🌶🌶 Medium Challenge: What happens if a user clicks “Add” without typing any numbers? Add an
if statement to your functions to show an error message if the inputs are empty. For division, also check that the second number is not 0.🌶🌶🌶 Spicy Challenge: Add a button that toggles between light and dark mode for the website.
For a summary of this lesson, check out the 12. JavaScript: Functions & The DOM One-Pager!