Skip to content

Lesson 21 of 50JavaScript in the browser

The DOM

See a web page as a tree of objects, then select, read, change, create and remove elements with JavaScript, safely.

16 min read0/5 questions

Everything you have written so far printed to a console. This lesson is where JavaScript starts changing what people actually see: the text on a page, which items are in a list, whether a menu is open. The browser makes that possible through the DOM, a live model of the page that your code can read and edit. Every framework you will meet later, React included, is built on top of the handful of methods in this lesson, so they are worth knowing well.

The page is a tree of objects

When the browser loads an HTML file, it does not keep the text. It parses it (reads it and works out its structure) and builds a tree of objects in memory. That tree is the Document Object Model, or DOM. Each element becomes an object called a node, and nodes nested inside another node are its children.

Take this small recipe card:

<body>
  <article class="recipe">
    <h2>Pancakes</h2>
    <ul>
      <li>2 eggs</li>
      <li>200 g flour</li>
    </ul>
  </article>
</body>
The recipe card as a DOM tree
documentheadh2text: Pancakeslitext: 2 eggslitext: 200 g flourularticle.recipebodyhtmlroot

document is the root. Your JavaScript reaches every other node through it.

1/4

Two ideas to hold on to. First, the DOM is live: change a node and the screen updates. Second, the DOM is not your HTML file. Edits happen in memory and vanish when the page reloads. You can see the current tree at any time in the browser devtools (right click, Inspect, the Elements panel).

Finding elements

Before you can change something, you need a reference to its node. Three methods cover nearly everything:

MethodReturnsWhen nothing matches
document.getElementById("price")The one element with that idnull
document.querySelector(".card h2")The first element matching a CSS selectornull
document.querySelectorAll("li")A NodeList of every matchAn empty NodeList

querySelector takes any CSS selector, the same ones you write in a stylesheet: "#total", ".recipe li", "input[type=email]", "ul > li:first-child". That makes it the one to reach for by default. A NodeList is a list-like object: it has length and forEach, and you can turn it into a real array with Array.from(list) or [...list] when you want map or filter.

You can also search inside an element instead of the whole page, which is handy when a page has several cards: card.querySelector("h2") only looks within card.

HTML & CSS
<article class="recipe"> <h2>Pancakes</h2> <ul> <li>2 eggs</li> <li>200 g flour</li> <li>300 ml milk</li> </ul> <p class="note"></p></article> <script> const card = document.querySelector(".recipe"); const title = card.querySelector("h2"); const items = card.querySelectorAll("li"); const note = card.querySelector(".note"); note.textContent = `${title.textContent} needs ${items.length} ingredients.`; items[0].style.fontWeight = "bold";</script>

Preview

Add a fourth <li> to the HTML and watch the count update. Then change "li" to "li:last-child" in querySelectorAll and see what items.length becomes.

Quick check
Your script runs document.querySelector('#cart').textContent = 'Empty' and throws TypeError: Cannot set properties of null. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

Reading and changing text

Every element has a textContent property: all the text inside it, with tags ignored. Reading it gives you a string; assigning to it replaces everything inside the element with plain text.

There is also innerHTML, which reads and writes the element's contents as an HTML string. Assigning to it makes the browser parse the string and build new nodes. It is powerful and, as you will see at the end of this lesson, dangerous with text you did not write yourself.

For form fields, the text the user typed is in value, not textContent. You will use that a lot in the forms lesson.

Attributes, classes and styles

Attributes are the name="value" pairs in your HTML. You can read and write any of them with getAttribute and setAttribute, and many common ones are also plain properties on the node:

const link = document.querySelector("a");
link.getAttribute("href"); // exactly what the HTML says, like "/about"
link.href; // the full resolved URL, like "https://example.com/about"
link.setAttribute("target", "_blank");
 
const img = document.querySelector("img");
img.alt = "A stack of pancakes with berries";
 
const panel = document.querySelector(".panel");
panel.hidden = true; // same as adding the hidden attribute

Custom data goes in data-* attributes, which you read through dataset. A data-product-id="42" attribute becomes el.dataset.productId (dashes turn into camelCase), and its value is always a string.

To change how something looks, prefer classes over inline styles. Keep the visual rules in CSS and let JavaScript switch classes on and off with classList:

  • el.classList.add("active") and el.classList.remove("active")
  • el.classList.toggle("active") adds it if missing, removes it if present, and returns true if the class is now on
  • el.classList.contains("active") checks without changing anything

The style property sets inline styles directly. CSS property names become camelCase (background-color is style.backgroundColor), and values are strings with units ("12px", not 12). It is fine for values that really are computed in JavaScript, like a progress bar width, but a class is easier to maintain for everything else.

The next example uses one line you have not met yet, addEventListener("click", ...), which means "run this function when the button is clicked". The events lesson covers it properly.

HTML & CSS
<style> .profile { display: flex; gap: 12px; align-items: center; padding: 12px; border: 1px solid #ccc; border-radius: 10px; } .avatar { width: 48px; height: 48px; border-radius: 50%; background: #c7d2fe; } button { padding: 6px 12px; } .following { background: #111; color: white; } .bar { height: 8px; background: #22c55e; margin-top: 12px; }</style> <div class="profile" data-user-id="7"> <div class="avatar"></div> <strong>Maya Chen</strong> <button>Follow</button></div><div class="bar"></div><p class="status"></p> <script> const profile = document.querySelector(".profile"); const button = profile.querySelector("button"); const status = document.querySelector(".status"); document.querySelector(".bar").style.width = "40%"; button.addEventListener("click", () => { const isOn = button.classList.toggle("following"); button.textContent = isOn ? "Following" : "Follow"; button.setAttribute("aria-pressed", String(isOn)); status.textContent = `User ${profile.dataset.userId}: ${isOn ? "followed" : "not followed"}`; });</script>

Preview

Click the button a few times. Then change "40%" to "85%", and try editing the .following rule in the CSS: the JavaScript does not change at all.

Predict the outputJavaScript

What does this print?

const el = document.createElement("div");
el.classList.add("open");
console.log(el.classList.toggle("open"));
Need a nudge? Hints walk you through it.

Creating and removing elements

To add something new, build it in three steps: create it, fill it in, and put it in the tree.

  1. document.createElement("li") makes a new, detached element. It exists in memory but is not on the page yet.
  2. Set its textContent, classes and attributes.
  3. Insert it. parent.append(child) adds at the end, parent.prepend(child) at the start, and el.before(other) or el.after(other) put a node next to el.

To take something away, call el.remove(). To empty a container, container.replaceChildren() with no arguments removes every child, and with arguments it swaps them all in one go.

A very common pattern is rendering a list from an array of data:

HTML & CSS
<style> table { border-collapse: collapse; width: 100%; } th, td { border-bottom: 1px solid #ddd; padding: 6px 8px; text-align: left; } .popular { background: #fef9c3; }</style> <h3>Plans</h3><table> <thead><tr><th>Plan</th><th>Price</th></tr></thead> <tbody id="plans"></tbody></table> <script> const plans = [ { name: "Starter", price: 0 }, { name: "Pro", price: 12, popular: true }, { name: "Team", price: 30 }, ]; const tbody = document.getElementById("plans"); for (const plan of plans) { const row = document.createElement("tr"); const name = document.createElement("td"); const price = document.createElement("td"); name.textContent = plan.name; price.textContent = plan.price === 0 ? "Free" : `$${plan.price}/month`; if (plan.popular) row.classList.add("popular"); row.append(name, price); tbody.append(row); }</script>

Preview

Add a fourth plan to the array. Move popular: true to a different plan. Then add tbody.firstElementChild.remove(); at the very end of the script and see which row disappears.

Every insertion changes the live page, and the browser has to work out the new layout before it can draw. For a few dozen rows that is not worth worrying about. For hundreds, it is tidier and often faster to build all the rows first and insert them in one call, either with tbody.append(...rows) or with a DocumentFragment (a lightweight container that is not on the page).

Put it in order4 steps

Put the steps for adding a new list item to the page in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

textContent, innerHTML and XSS

Here is why innerHTML deserves care. Suppose a comments section shows whatever a visitor typed. If you insert that text with innerHTML, the browser treats it as HTML, and HTML can run code. This attack is called XSS (cross-site scripting): an attacker gets their script to run on your page, where it can read what the user sees, act as them, or redirect them.

The example uses a fake comment that contains an image with a broken src and an onerror attribute. The browser runs onerror when the image fails to load.

HTML & CSS
<h3 id="title">Comments</h3><p><strong>Safe (textContent):</strong> <span id="safe"></span></p><p><strong>Unsafe (innerHTML):</strong> <span id="unsafe"></span></p> <script> const comment = `Great recipe! <img src="nope" onerror="document.getElementById('title').textContent = 'This page was hijacked'">`; document.getElementById("safe").textContent = comment; document.getElementById("unsafe").innerHTML = comment;</script>

Preview

The safe line shows the comment as harmless text, angle brackets and all. The unsafe line builds a real img element, its onerror code runs, and it rewrites the heading. A real attacker would do something worse than change a heading.

The rules that keep you safe:

  • Use textContent (or createElement plus textContent) for anything that came from a user, a URL, or an API.
  • Only use innerHTML with strings you wrote yourself, like a fixed template.
  • If you truly need to show user-written HTML (a rich text editor, say), clean it with a well-tested sanitizer library such as DOMPurify first.
Quick check
A search page shows You searched for: <query> using the query from the URL. Which line is safe?
Need a nudge? A hint rules out a wrong answer.

Where the script goes

A script can only find elements that already exist when it runs. The browser builds the DOM from top to bottom, so a <script> in the head that runs immediately finds an almost empty body. Two fixes:

  • Put the <script> at the end of body, as every example on this page does.
  • Or keep it in the head with defer: <script src="app.js" defer></script>. The file downloads in parallel and runs once the whole document has been parsed. This is the usual choice for real sites.
Match the pairs0/5 matched

Match each task to the tool for it.

Choose an item, then its match on the other side.
Key terms
DOM
Document Object Model: the live tree of objects the browser builds from HTML, which JavaScript can read and change.
node
One object in the DOM tree, such as an element or a piece of text.
querySelector
Returns the first element matching a CSS selector, or null if none match.
NodeList
The list-like result of querySelectorAll. It has length and forEach; spread it into an array for map or filter.
classList
An element's classes, with add, remove, toggle and contains methods.
dataset
An object holding an element's data-* attributes, with dashed names turned into camelCase.
XSS
Cross-site scripting: an attacker's code running on your page, often through untrusted text inserted with innerHTML.