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.
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>document is the root. Your JavaScript reaches every other node through it.
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:
| Method | Returns | When nothing matches |
|---|---|---|
document.getElementById("price") | The one element with that id | null |
document.querySelector(".card h2") | The first element matching a CSS selector | null |
document.querySelectorAll("li") | A NodeList of every match | An 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.
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.
document.querySelector('#cart').textContent = 'Empty' and throws TypeError: Cannot set properties of null. What is the most likely cause?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 attributeCustom 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")andel.classList.remove("active")el.classList.toggle("active")adds it if missing, removes it if present, and returnstrueif the class is now onel.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.
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.
What does this print?
const el = document.createElement("div");
el.classList.add("open");
console.log(el.classList.toggle("open"));Creating and removing elements
To add something new, build it in three steps: create it, fill it in, and put it in the tree.
document.createElement("li")makes a new, detached element. It exists in memory but is not on the page yet.- Set its
textContent, classes and attributes. - Insert it.
parent.append(child)adds at the end,parent.prepend(child)at the start, andel.before(other)orel.after(other)put a node next toel.
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:
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 the steps for adding a new list item to the page in order.
- Tap the steps below in the right order.
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.
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(orcreateElementplustextContent) for anything that came from a user, a URL, or an API. - Only use
innerHTMLwith 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.
You searched for: <query> using the query from the URL. Which line is safe?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 ofbody, as every example on this page does. - Or keep it in the
headwithdefer:<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 each task to the tool for it.
- 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.