18.1 Creating a Vite Project
For seventeen days, every program you wrote printed lines of text in a terminal. That is how most tools and servers work, but it is not what most people mean by an app. An app is a page in a browser, with headings, lists and buttons, that changes while you look at it. Today your TypeScript moves into the browser.
That raises two problems. First, a browser runs JavaScript, not TypeScript: it does not understand type annotations. Second, a browser opens web pages, not .ts files, so something has to serve your page and your code to it. Node solved the first problem for you since Day 1 by stripping the types before running a file. In the browser, a tool called Vite (French for “quick”, said “veet”) solves both. Vite is a development server: a program that runs on your own computer, hands your page to the browser, removes the types from your TypeScript as the browser asks for it, and reloads the page every time you save a file.
You do not install Vite by hand. npm has a command that creates a whole new project from a template, a ready-made starting project. Open a terminal in the folder where you keep your day folders, and run:
npm create vite@latest day18 -- --template vanilla-ts
Read it piece by piece:
| Part | What it means |
|---|---|
npm create vite@latest |
Download the newest version of Vite’s project creator and run it |
day18 |
The name of the new project folder |
-- |
Everything after this goes to Vite’s creator, not to npm |
--template vanilla-ts |
Use the template called vanilla-ts: plain TypeScript with no extra framework (“vanilla” means plain, nothing added) |
Depending on the version, the creator may ask one or two more questions. If it offers to install the packages and start the project for you, saying yes does the next two steps for you. Otherwise, run them yourself:
cd day18
npm install
npm run dev
npm install reads the new project’s package.json and downloads Vite and TypeScript into node_modules, exactly as on Day 13. npm run dev runs the dev script from package.json, which starts Vite’s server. The terminal shows an address such as http://localhost:5173/. localhost is the name every computer uses for itself, so this address means “the server running on this computer”. Hold Ctrl (Cmd on a Mac) and click the address, or type it into your browser. You see Vite’s starter page.
Leave that terminal running: the server lives as long as the command does. Press Ctrl+C in it when you want to stop the server, and run npm run dev again to restart it. Open a second terminal in VS Code (the + button in the terminal panel) for every other command today.
Open the day18 folder in VS Code. The template made several files. These are the ones that matter today:
| File | What it is |
|---|---|
index.html |
The page the browser opens |
src/main.ts |
The TypeScript that runs on that page |
src/style.css |
The rules for how the page looks |
package.json |
The project’s scripts (dev, build) and packages |
tsconfig.json |
The checker’s settings, with "DOM" in its lib list so the checker knows about browser pages |
The template also made a starter counter and a few pictures; you will replace them in the next subsection.
Worked example: Seeing the reload
With the server running and the page open, open index.html in VS Code. Somewhere inside it you will find a line containing <title>. Change the text between <title> and </title> to Day 18, and save. Look at the browser tab: its name changed without you touching the browser. Vite noticed the save and told the page to reload.
Now try a mistake. Open src/main.ts, add the line const count: number = "three"; at the bottom, and save. The page still reloads and still works. Vite only strips types, like node did; it never checks them. In the second terminal, run:
npx tscThe checker reports a TS2322 error on that line, just as it would have on Day 2. The rule from Day 1 still holds, in a new place: npx tsc checks, and something else runs. Here the something else is the browser. Delete the line before you go on.
Key idea
npm create vite@latest makes a project from a template, and npm run dev starts a development server that serves
the page to your browser and reloads it on every save. Vite strips types but never checks them, so keep running npx tsc yourself.
Watch out
Thinking a working page means correct types. Because Vite does not check types, a page can load and look fine while npx tsc reports errors, and a type error the checker would have caught becomes a bug the user finds. Make npx tsc part of every change, in the second terminal. (The template’s build script runs tsc before it builds the finished site, so errors do stop a build; they just never stop npm run dev.)
Pause and try
Question 1 · Multiple choice
Vite’s server is running, and you save main.ts with a line that assigns a string to a number variable. What happens?
- Vite refuses to reload the page and shows the type error in the browser
- The page reloads; the type error appears only when you run
npx tsc - The terminal running
npm run devstops with the type error - Nothing reloads until you run
npm installagain
Check your reasoning
B. Vite strips the annotations and serves the JavaScript that is left; it never asks whether the types are right. Only the checker does that, and only when you run npx tsc.
- A and C are wrong because they describe a tool that checks types, and Vite’s development server does not.
- D is wrong:
npm installdownloads packages. It has nothing to do with reloading, which happens on every save.
Reread 18.1 Creating a Vite Project if you chose differently.
18.2 How the Page Loads Your Script
The browser opens index.html. Your code is in src/main.ts. Something has to connect the two, and to understand that connection you need to read a little of the language web pages are written in.
A web page is written in HTML (HyperText Markup Language): ordinary text with labels around it that say what each piece is. Each label is a tag, a name between angle brackets. Most pieces of a page are written as an opening tag, the content, and a closing tag with a slash:
<h1>My tasks</h1>
The opening tag <h1>, the content My tasks, and the closing tag </h1> together make one element: one piece of the page, here a top-level heading. Elements can hold other elements, which is how a list holds its items:
<ul>
<li>Water the plants</li>
<li>Pay the phone bill</li>
</ul>
An opening tag can also carry attributes: extra settings written as name="value" after the tag name. Two attributes matter on every page:
idgives one element a unique name, so code can find exactly that element:<ul id="tasks">. No two elements on a page should share anid.classgives an element one or more group labels, separated by spaces, which any number of elements can share:<li class="done urgent">.
A few elements, such as <input>, hold no content and have no closing tag. These are the elements you will meet today:
| Tag | What it shows |
|---|---|
<h1>, <h2> |
A heading, and a smaller heading |
<p> |
A paragraph of text |
<ul>, <ol>, <li> |
A bulleted list, a numbered list, a list item |
<strong>, <em>, <b> |
Important, stressed, and bold text inside a line |
<a> |
A link |
<button> |
A button |
<input> |
A box the user can type in |
<div> |
A box that groups other elements, with no look of its own |
<table>, <tr>, <th>, <td> |
A table, a row, a heading cell, a data cell |
Now open index.html. It looks something like this (your copy may differ in small ways):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Day 18</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
The whole page is one <html> element with two children. <head> holds information about the page, such as the tab title, which is not shown in the page itself. <body> holds everything the user sees. Inside the body are two elements, and the second one is the connection you were looking for:
| Piece | What it does |
|---|---|
<script> |
Tells the browser “run some code here” |
src="/src/main.ts" |
Where the code is: the file src/main.ts in the project |
type="module" |
Treat the code as a module, so it can import, as on Day 13, and run only after the whole page has been read |
When the browser reaches this tag it asks Vite’s server for /src/main.ts. Vite reads your file, strips the types, and sends back plain JavaScript, which the browser runs. Because the script is a module, the browser waits until it has read the entire HTML before running it, so every element in the body already exists when your first line runs. The chain is:
browser opens index.html -> reads the body -> finds the script tag
-> asks Vite for /src/main.ts -> Vite strips the types -> browser runs the code
Code that runs in the browser still has console.log, but its output goes to the browser’s console, not to your terminal. Open it with F12 (or right-click the page, choose Inspect, and pick the Console tab).
Trying this page’s examples. Every browser example on this page comes in two files. The page file, such as first-script.html, is only the inside of the body. The script file, such as first-script.dom.ts, is what goes in main.ts (the .dom.ts name only marks it as a browser script on this page). To try one:
- In
index.html, replace the line<div id="app"></div>with the example’s page. Keep the<script>line below it. - Delete everything in
src/main.ts, and type in the example’s script. - Save both. The browser reloads; open the console to see any
console.logoutput.
Worked example: Your first browser script
Here is the page and the script:
<h1>My tasks</h1>
<p>Nothing to do yet.</p>console.log("main.ts is running");
console.log(2 + 3);The browser shows the heading and the paragraph from the HTML; the script does not change them. The console shows:
main.ts is running
5This is the same console.log from Day 1, running in a new place. Change line 2 to console.log(2 + "3");, save, and watch the console: the page reloaded, the script ran again from the top, and it shows 23.
Key idea
An HTML page is made of elements, written as tags with attributes such as id and class. The
<script type="module" src="/src/main.ts"> tag in index.html makes the browser fetch main.ts from Vite and run it after
the whole page has been read.
Watch out
Running a page script with node. node main.ts runs a file in a terminal, where there is no page at all. Code that uses the page, which is everything from the next subsection on, cannot work there. Browser code runs in the browser, through the <script> tag and npm run dev.
Pause and try
Question 2 · Multiple choice
In <script type="module" src="/src/main.ts"></script>, what does src tell the browser?
- Which element of the page the script is allowed to change
- Where to fetch the code to run
- That the code is TypeScript, so the browser should check its types
- The name of the function to call first
Check your reasoning
B. src (source) is the address of the code. The browser asks the server for /src/main.ts, and Vite answers with the stripped JavaScript.
- A is wrong: a script can reach any element on its page.
- C is wrong: browsers never check types, and Vite strips them without checking.
- D is wrong: a script runs from its first line to its last, like every program since Day 1.
Reread 18.2 How the Page Loads Your Script if you chose differently.
Question 3 · Short answer
A classmate says, “The <script> line should go at the very top of the body, so the code starts sooner.” Explain why that would not help, and why it does not break anything either.
Check your reasoning
Model answer: A type="module" script always waits until the browser has read the whole HTML, wherever its tag is, so moving it up does not make it start sooner. For the same reason it does not break anything: when the code runs, every element in the body exists, wherever the tag sits.
A complete answer says that module scripts run only after the entire page has been read.
Reread 18.2 How the Page Loads Your Script if your answer differed.
18.3 The DOM as a Tree
HTML is text, and text is hard to change: to add an item to a list, a program would have to find the right spot in a long string and insert characters there. So when the browser reads the HTML, it does not keep the text. It builds a set of objects, one for each element, linked to each other the way the elements were nested. Your code works with those objects.
That set of objects is the DOM (Document Object Model). It is a tree: a structure where every item, except the one at the top, sits inside exactly one other item. Programmers borrow family words for it. An element directly inside another is its child, the element it sits in is its parent, and children of the same parent are siblings. The item at the top is the document, the whole page, and your code reaches it through a ready-made variable called document.
Here is a small page:
<h1>Weekend plans</h1>
<ul id="plans">
<li>Bike ride</li>
<li>Bake bread</li>
</ul>
<p class="note">Rain is likely on Sunday.</p>and the tree the browser builds from it, including the parts Vite’s index.html adds around it (the script tag is left out to keep the picture small):
document
html
head
title
body
h1 "Weekend plans"
ul id="plans"
li "Bike ride"
li "Bake bread"
p class="note" "Rain is likely on Sunday."
Each indented line is a child of the line above it with less indentation. The body has three children: h1, ul and p. The ul is their sibling, and it is also the parent of the two li elements. The words in quotes are the text inside an element; in the DOM, text is stored as its own small item, a text node, inside the element.
Worked example: Walking the body's children
document.body is the body element. Every element has a children property, which lists its child elements in order, and a tagName property, which holds its tag name. children can be looped over with for...of, like an array:
console.log(document.body.children.length);
for (const child of document.body.children) {
console.log(child.tagName, child.children.length);
}3
H1 0
UL 2
P 0- Line 1: the body has three child elements, so
children.lengthis 3. - Lines 2 to 4:
for...ofvisits the children in page order, as it visits an array’s elements. For each one, the loop shows itstagNameand how many children it has. The browser gives tag names in capitals. H1 0: the heading holds only text. Text is a text node, not an element, so it is not counted inchildren.UL 2: the list holds twolielements.
The page itself does not change; the script only reads the tree.
The tree is live: when code changes an object in it, the browser redraws the page to match, straight away. That is the whole idea of today. You will never edit index.html from code; you change the DOM, and the page follows. You can watch it: in the browser’s developer tools, the Elements tab shows the current DOM tree, not the original file, and later in this lesson you will see your code’s changes appear there.
Key idea
The browser turns the HTML into the DOM: a tree of objects, one per element, starting at document. Code reads and
changes the DOM, and the page on screen always shows the DOM as it is now.
Watch out
Counting text as children. children holds only elements. The words inside <h1>Weekend plans</h1> are a text node, so the heading has 0 children. Students who count the text get H1 1, and later look for the text in the wrong place. Text is read with textContent, which 18.4 introduces.
Pause and try
Question 4 · Tracing
Draw the tree for this page, then predict exactly what the script shows in the console.
<div id="card">
<h2>Ana Lee</h2>
<p>Team captain</p>
</div>
<ol>
<li>Warm up</li>
<li>Drills</li>
<li>Match</li>
</ol>console.log(document.body.children.length);
for (const child of document.body.children) {
console.log(child.tagName, child.children.length);
}Check your reasoning
body
div id="card"
h2 "Ana Lee"
p "Team captain"
ol
li "Warm up"
li "Drills"
li "Match"2
DIV 2
OL 3The body has two children, the div and the ol. The div holds two elements (h2 and p), and the ol holds three lis. The grandchildren are not counted in the body’s children: children lists only the elements directly inside.
Reread 18.3 The DOM as a Tree if your numbers differed.
18.4 Finding Elements with querySelector
Walking children by hand works for a tiny page, but on a real page the element you want may sit ten levels down. You need a way to say “the element with id title” and get it, wherever it is.
document.querySelector(selector) searches the whole tree, in page order, and gives back the first element that matches the selector. A selector is a short string that describes which elements you mean. Selectors come from CSS, the language for styling pages, and a handful cover almost everything:
| Selector | Matches | Example match |
|---|---|---|
"#title" |
The element whose id is title |
<h1 id="title"> |
".status" |
Elements whose class includes status |
<p class="status big"> |
"li" |
Elements with that tag name | <li> |
"#plans li" |
li elements anywhere inside the element with id plans |
an li inside <ul id="plans"> |
# means id and . means class. A space between two selectors means “inside”. Selectors are case-sensitive in their ids and classes: "#Title" does not match id="title".
What happens if nothing matches? There is no element to give back, so querySelector gives back null. That means its type, as the checker sees it, is Element | null. Element is the type of any element in the tree, and it has the properties every element shares, such as children, tagName, and textContent: the text inside the element, which you can read or assign. Because of the | null, you meet Day 9’s rule again: before you use the result, you narrow it.
Worked example: Changing a heading
<h1 id="title">Hello</h1>
<p class="status">Loading</p>const title = document.querySelector("#title");
if (title === null) {
throw new Error("No #title element on the page");
}
title.textContent = "Welcome back, Ana";
const status = document.querySelector(".status");
if (status !== null) {
status.textContent = "3 tasks due today";
}The page now shows “Welcome back, Ana” and “3 tasks due today”. In the DOM, the body became:
<h1 id="title">Welcome back, Ana</h1>
<p class="status">3 tasks due today</p>- Line 1:
titlehas the typeElement | null. - Lines 2 to 4: if it is
null, Day 16’sthrowstops the script with a message that names the problem. After theif, the checker knowstitlecannot benull, so it narrows the type toElement. - Line 5: assigning
textContentreplaces the heading’s text. The DOM changes, and the browser redraws the heading. - Lines 7 to 10: the other way to narrow. Here the status line is optional, so instead of stopping, the script only changes it when it exists.
Which way should you narrow? An element your page cannot work without, such as the list your whole app draws into, should throw: if it is missing, the HTML and the code disagree, and you want to hear about it at once, in the console, with your own message. An element that is only nice to have can use if (x !== null).
Now vary the selector. This script asks for an id that is not on the page, and for a class that two elements share:
<ul>
<li class="item">Bike ride</li>
<li class="item">Bake bread</li>
</ul>const missing = document.querySelector("#subtitle");
console.log(missing);
const firstItem = document.querySelector(".item");
console.log(firstItem?.textContent);null
Bike ride
There is no #subtitle, so missing is null, exactly the value the type warned about. Both lis have the class item, and querySelector stops at the first one in page order. Line 5 uses Day 9’s ?.: if firstItem were null, it would show undefined instead of crashing.
Watch out
Using the result without narrowing.
const title = document.querySelector("#title");
title.textContent = "Welcome back, Ana";npx tsc reports:
heading-null.dom.ts:2:1 - error TS18047: 'title' is possibly 'null'.This is Day 9’s message, now pointing at the page. The checker cannot see your HTML; it does not know there is an #title in index.html, and next week someone might rename it. If the code ran anyway on a page without that element, the browser would stop with a TypeError about setting a property of null, and the line that failed would tell you nothing about which element was missing. Narrow with if (title === null) { throw new Error("No #title element on the page"); } so the failure, if it ever comes, names the element.
Key idea
document.querySelector(selector) gives the first matching element, or null when nothing matches, so its type is
Element | null. Narrow it with throw for elements the page needs, or if (x !== null) for optional ones, before
you use textContent or any other property.
Pause and try
Question 5 · Tracing
Predict exactly what this script shows. Watch for ids, classes, and capital letters.
<h1 class="big">Scores</h1>
<ul id="scores">
<li>Ana 31</li>
<li class="big">Ben 25</li>
</ul>
<p id="best">Best: Ana</p>console.log(document.querySelector(".big")?.textContent);
console.log(document.querySelector("li")?.textContent);
console.log(document.querySelector("#scores .big")?.textContent);
console.log(document.querySelector("#Best")?.textContent);Check your reasoning
Scores
Ana 31
Ben 25
undefined- Line 1: two elements have the class
big, theh1and the secondli. Theh1comes first in the page, so it wins. - Line 2: the first
liin the page is Ana’s. - Line 3: “an element with class
biginside#scores”. Theh1is not inside the list, so the match is Ben’sli. - Line 4: ids are case-sensitive, so
#Bestmatches nothing.querySelectorgivesnull, and?.turns that intoundefinedinstead of a crash.
Reread 18.4 Finding Elements with querySelector if any line differed.
Question 6 · Multiple choice
const total = document.querySelector("#total"); and the page definitely has an element with id total. What type does the checker give total?
Element, because the element existsElement | null, because the checker cannot see the HTMLHTMLElement | undefinedstring, the text inside the element
Check your reasoning
B. The checker reads only your TypeScript. It has no idea what index.html contains, so it must allow for the case where nothing matches, which querySelector reports as null.
- A is wrong: the type comes from
querySelectoritself, not from the page, which the checker never sees. - C is wrong twice: a missing element is
null, notundefined, and an#idselector gives the generalElementtype. - D is wrong:
querySelectorgives back the element object; its text is the separatetextContentproperty.
Reread 18.4 Finding Elements with querySelector if you chose differently.
18.5 Element Types and the Generic Form
Element has what every element shares. But a text box has a value (what is typed in it), a button can be disabled, and a list has its own features. Those properties belong to more specific types, and the checker only allows them on the right type.
The browser describes elements with Day 15’s classes, arranged with extends. Each class adds what its kind of element has to what its parent class already had:
Element children, tagName, textContent, classList, ...
HTMLElement adds what every HTML element has, such as hidden
HTMLInputElement adds value, ...
HTMLButtonElement adds disabled, ...
HTMLUListElement a ul list
HTMLLIElement a list item
HTMLParagraphElement a p paragraph
HTMLHeadingElement h1 to h6
Because HTMLInputElement extends HTMLElement, and HTMLElement extends Element, an input is an HTMLElement and is an Element, and has everything both of those have, as on Day 15.
When the selector is a bare tag name, the checker can work out the specific type itself: document.querySelector("ul") has the type HTMLUListElement | null, because anything matching "ul" must be a ul. With an id or class, it cannot: "#name" might be any kind of element, so you get the general Element | null, and the specific properties are not allowed:
const nameInput = document.querySelector("#name");
if (nameInput === null) {
throw new Error("No #name element on the page");
}
console.log(nameInput.value);input-value.dom.ts:5:23 - error TS2339: Property 'value' does not exist on type 'Element'.
This is the “no such property” message from Day 7. nameInput is narrowed to Element, and Element has no value. You know it is an input; you have to tell the checker.
The generic form. querySelector is a generic function, like the ones you wrote on Day 14. You can pass it a type argument in angle brackets: document.querySelector<HTMLInputElement>("#name"), whose type is HTMLInputElement | null. You still narrow away the null, and after that, value is allowed.
Worked example: Reading an input and disabling a button
<input id="name" value="Ana">
<button id="save" type="button">Save</button>
<p id="message"></p>const nameInput = document.querySelector<HTMLInputElement>("#name");
const saveButton = document.querySelector<HTMLButtonElement>("#save");
const message = document.querySelector("#message");
if (nameInput === null || saveButton === null || message === null) {
throw new Error("The page is missing an element");
}
message.textContent = `Saving ${nameInput.value}`;
saveButton.disabled = true;
saveButton.textContent = "Saving";After the script, the body is:
<input id="name" value="Ana" />
<button id="save" type="button" disabled="">Saving</button>
<p id="message">Saving Ana</p>- Lines 1 and 2: the generic form gives
HTMLInputElement | nullandHTMLButtonElement | null. Line 3 leavesmessageasElement | null, because it only needstextContent, which every element has. - Lines 4 to 6: one
ifwith||narrows all three. After it, none of them can benull. - Line 8:
nameInput.valueis the text in the box,"Ana", astring. - Line 9:
disabledis abooleanproperty of buttons. Setting it totruegreys the button out so it cannot be clicked, and the browser records it in the DOM as adisabledattribute.
There is a catch, and Day 16 warned about it. The type argument is a promise you make, exactly like an as assertion: the checker cannot see the page, so it believes you. If the promise is false, nothing stops you:
const wrong = document.querySelector<HTMLInputElement>("#message");
if (wrong !== null) {
console.log(typeof wrong.value);
}undefined
On the same page, #message is a paragraph, not an input. npx tsc accepts the program, because the type argument says HTMLInputElement, and to the checker wrong.value is a string. At runtime, a paragraph has no value, and typeof shows undefined. Call .toUpperCase() on it and the script crashes.
When you want the browser to check what kind of element it found, use Day 16’s instanceof. Every element is an instance of its class, so instanceof HTMLInputElement asks the real question at runtime, and the checker narrows the type to match:
const field = document.querySelector("#name");
if (!(field instanceof HTMLInputElement)) {
throw new Error("#name is not an input");
}
console.log(field.value.toUpperCase());
const notAnInput = document.querySelector("#save");
console.log(notAnInput instanceof HTMLInputElement);
console.log(notAnInput instanceof HTMLButtonElement);
console.log(notAnInput instanceof HTMLElement);ANA
false
true
true
- Lines 2 to 4: if
fieldis not anHTMLInputElement(andnullis not), the script stops. After theif,fieldis anHTMLInputElement, so line 5 may usevalue. - Lines 7 to 10: the
#savebutton is not an input, it is anHTMLButtonElement, and, because ofextends, it is also anHTMLElement.
| Way to get a specific type | Checked at runtime? | Use it when |
|---|---|---|
A tag selector: querySelector("ul") |
Yes, by the selector | The element’s tag is the selector |
The generic form: querySelector<HTMLInputElement>("#name") |
No, it is a promise | You wrote the HTML and the id clearly names that kind of element |
instanceof HTMLInputElement |
Yes | You want a wrong page to fail with your own message |
Key idea
Specific properties such as value and disabled belong to specific element classes (HTMLInputElement,
HTMLButtonElement), which extend HTMLElement and Element. Get the specific type from a tag selector, from the
generic form querySelector<HTMLInputElement>(…), which the checker trusts without checking, or from instanceof,
which the browser checks.
Pause and try
Question 7 · Multiple choice
Which declaration gives box the type HTMLInputElement | null?
const box = document.querySelector("#email");const box = document.querySelector("input");const box: HTMLInputElement = document.querySelector("#email");const box = document.querySelector<HTMLElement>("#email");
Check your reasoning
B. A bare tag selector tells the checker the element’s kind: anything matching "input" is an HTMLInputElement, and | null covers no match.
- A is wrong: with an id selector, the checker only knows it is some
Element, so the type isElement | null. - C is wrong: the annotation leaves out
| null, butquerySelectorcan always givenull, sonpx tscrejects the line with TS2322. The annotation cannot make a missing element impossible. - D is wrong: the type argument is
HTMLElement, so the type isHTMLElement | null, which has novalue.
Reread 18.5 Element Types and the Generic Form if you chose differently.
Question 8 · Short answer
wrong-generic.dom.ts passes npx tsc and yet wrong.value is undefined at runtime. Explain why the checker let it through, and how instanceof would have changed what happens.
Check your reasoning
Model answer: The type argument <HTMLInputElement> is a promise, like an as assertion. The checker cannot see the HTML, so it takes the promise and treats wrong as an input whose value is a string. The element is really a paragraph, which has no value. With if (!(wrong instanceof HTMLInputElement)) { throw … }, the browser would check the real element when the script runs, find a paragraph, and stop with a clear message instead of carrying on with undefined.
A complete answer says that the generic form is not checked against the page, and that instanceof is checked at runtime.
Reread 18.5 Element Types and the Generic Form if your answer differed.
18.6 textContent Versus innerHTML
You have been putting text on the page with textContent. Elements have a second property that looks like it does the same job, and it is one of the most famous sources of security holes on the web. You need to know both, and why one is safe.
innerHTML is the content of an element written as HTML. Assigning a string to it makes the browser read the string as HTML: any tags in it become real elements. textContent treats the string as plain text: any < and > in it are shown as the characters < and >, never turned into elements.
Worked example: The same string, two ways
<p id="as-text"></p>
<p id="as-html"></p>const comment = "I <b>love</b> this recipe";
const asText = document.querySelector("#as-text");
const asHtml = document.querySelector("#as-html");
if (asText === null || asHtml === null) {
throw new Error("The page is missing a paragraph");
}
asText.textContent = comment;
asHtml.innerHTML = comment;
console.log(asText.children.length, asHtml.children.length);
console.log(asHtml.textContent);The page shows two lines. The first reads, character for character, I <b>love</b> this recipe. The second reads “I love this recipe”, with “love” in bold. In the DOM:
<p id="as-text">I <b>love</b> this recipe</p>
<p id="as-html">I <b>love</b> this recipe</p>and the console shows:
0 1
I love this recipe- Line 8:
textContentstores the string as one text node. To show it, the browser writes<as<(“less than”) and>as>in its HTML, which is how HTML spells those characters when they are text, not tags. - Line 9:
innerHTMLreads the string as HTML, so<b>love</b>becomes a realbelement. - Line 10: the first paragraph has no child elements; the second has one, the
b. - Line 11: reading
textContentgives all the text inside an element, including the text inside its children, with the tags left out.
Now imagine the string did not come from you. A comments page shows each visitor’s comment, and one visitor types this as their comment:
const comment = '<img src="nothing.png" onerror="alert(\'Gotcha\')">';
commentBox.innerHTML = comment;
With innerHTML, the browser builds a real image element. The image file does not exist, so the browser runs the code in its onerror attribute: a stranger’s code, running on your page, for every person who views that comment. Here it only shows a pop-up, but the same trick can read what other visitors type into the page or act as them. This attack is called cross-site scripting, and it starts with putting someone else’s text into innerHTML. With textContent, the same comment is shown harmlessly as the characters the visitor typed.
So the rule is short: text from users goes in textContent, always. innerHTML is only for HTML you wrote yourself, and even then, creating elements in code, as in the next subsection, is usually clearer. The checker cannot help you here: both properties accept any string.
Key idea
textContent sets plain text: tags in the string are shown, never run. innerHTML reads the string as HTML and
builds elements from it, which lets anyone whose text reaches it put code on your page. Use textContent for any text
you did not write.
Watch out
Building HTML with a template literal. It is tempting to write item.innerHTML = `<strong>${name}</strong>`, because one line makes the bold title. If name came from a user, that line has the hole above. Make the strong element with createElement and put name in its textContent instead; 18.7 shows how, and the Putting it together example does exactly this.
Pause and try
Question 9 · Tracing
Predict exactly what this script shows in the console, and what the #out paragraph looks like in the DOM afterwards.
<div id="note">
<h2>Reminder</h2>
<p>Bring a <em>packed</em> lunch</p>
</div>
<p id="out"></p>const lunch = document.querySelector("#note p");
const out = document.querySelector("#out");
if (lunch === null || out === null) {
throw new Error("The page is missing an element");
}
console.log(lunch.textContent);
out.textContent = "<em>Done</em>";
console.log(out.children.length);Check your reasoning
Bring a packed lunch
0<p id="out"><em>Done</em></p>- Line 1:
"#note p"is the paragraph inside thediv. - Line 7: reading
textContentcollects the text of the paragraph and of theeminside it, without the tags. - Line 8: assigning to
textContentmakes the string plain text, so the page shows the characters<em>Done</em>, and the paragraph has no child elements (line 9 shows0).
Reread 18.6 textContent Versus innerHTML if either part differed.
Question 10 · Multiple choice
A page shows a greeting with a name that each visitor types in. greeting is an HTMLElement. Which line is safe?
greeting.innerHTML = "Hello, " + visitorName;greeting.innerHTML = `Hello, ${visitorName}`;greeting.textContent = `Hello, ${visitorName}`;- All three are safe, because
npx tscaccepts them
Check your reasoning
C. textContent shows the whole string as text, so a “name” full of tags is shown as characters and never becomes elements or runs.
- A and B are wrong: both hand the visitor’s text to
innerHTML, which builds elements from it, so a name like animgtag with anonerrorattribute runs its code. A template literal and+make the same string. - D is wrong: both properties accept any
string, so the checker has nothing to complain about. Safety here is your job, not the checker’s.
Reread 18.6 textContent Versus innerHTML if you chose differently.
18.7 Creating, Adding, and Removing Elements
So far, scripts changed elements that the HTML already had. But an app does not know in advance how many tasks, messages or products it will show; it has to make elements while it runs.
Making an element and showing it are two separate steps:
document.createElement(tagName)makes a new element object. It is not in the tree yet, so it is not on the page.parent.append(child)puts it into the tree as the last child ofparent. Now the page shows it.
The checker types createElement from the tag name, the same way it types a tag selector: document.createElement("li") gives an HTMLLIElement, with no | null, because making an element cannot fail. The reverse of append is element.remove(), which takes an element out of the tree, along with everything inside it.
Worked example: Updating a shopping list
<ul id="shopping">
<li id="old">Old batteries</li>
</ul>const list = document.querySelector<HTMLUListElement>("#shopping");
const old = document.querySelector("#old");
if (list === null || old === null) {
throw new Error("The page is missing an element");
}
const milk = document.createElement("li");
milk.textContent = "Milk";
list.append(milk);
const eggs = document.createElement("li");
eggs.textContent = "Eggs";
list.append(eggs);
old.remove();
console.log(list.children.length);2After the script, the body is:
<ul id="shopping">
<li>Milk</li>
<li>Eggs</li>
</ul>| Line | What happens | Children of the list |
|---|---|---|
| 1–5 | Find the list and the old item, and narrow both | Old batteries |
| 7–8 | Make a new li holding “Milk”; it exists only as an object |
Old batteries |
| 9 | Append it: it becomes the list’s last child and appears on the page | Old batteries, Milk |
| 11–13 | The same for “Eggs” | Old batteries, Milk, Eggs |
| 15 | Remove the old item from the tree | Milk, Eggs |
Now vary what you append. An element can only be in one place in the tree. Appending an element that is already in the tree does not copy it; it moves it. And append accepts several arguments at once, including strings, which become text nodes:
<h2>To do</h2>
<ul id="todo">
<li id="laundry">Laundry</li>
<li>Dishes</li>
</ul>
<h2>Done</h2>
<ul id="done"></ul>const todo = document.querySelector<HTMLUListElement>("#todo");
const done = document.querySelector<HTMLUListElement>("#done");
const laundry = document.querySelector("#laundry");
if (todo === null || done === null || laundry === null) {
throw new Error("The page is missing an element");
}
done.append(laundry);
const note = document.createElement("li");
note.append("Vacuum", " the hall");
todo.append(note);
console.log(todo.children.length, done.children.length);2 1
<h2>To do</h2>
<ul id="todo">
<li>Dishes</li>
<li>Vacuum the hall</li>
</ul>
<h2>Done</h2>
<ul id="done">
<li id="laundry">Laundry</li>
</ul>
Line 8 takes the Laundry item, which was in the to-do list, and appends it to the done list. It left the to-do list as it arrived in the done list. Line 10 appends two strings to the new item, which together make its text, “Vacuum the hall”. Line 11 adds that item at the end of the to-do list.
Watch out
Creating an element and never appending it.
const list = document.querySelector<HTMLUListElement>("#shopping");
if (list === null) {
throw new Error("No #shopping list on the page");
}
const milk = document.createElement("li");
milk.textContent = "Milk";
console.log(list.children.length);1npx tsc is happy and nothing crashes, but Milk never appears: the list still has only its Bread item. createElement only made an object; until it is appended somewhere in the tree, the page does not know it exists. Every createElement needs a matching append.
Key idea
document.createElement("li") makes a typed element that is not on the page yet; parent.append(…) adds elements or
strings as the parent’s last children, moving an element that was already in the tree; element.remove() takes an
element off the page.
Pause and try
Question 11 · Tracing
Predict exactly what the console shows, and what the two lists hold afterwards.
<ul id="a">
<li id="one">One</li>
<li id="two">Two</li>
</ul>
<ul id="b"></ul>const listA = document.querySelector<HTMLUListElement>("#a");
const listB = document.querySelector<HTMLUListElement>("#b");
const one = document.querySelector("#one");
const two = document.querySelector("#two");
if (listA === null || listB === null || one === null || two === null) {
throw new Error("The page is missing an element");
}
listB.append(one);
listA.append(one);
two.remove();
const three = document.createElement("li");
three.textContent = "Three";
listB.append(three);
console.log(listA.children.length, listB.children.length);Check your reasoning
1 1<ul id="a">
<li id="one">One</li>
</ul>
<ul id="b">
<li>Three</li>
</ul>| Line | What happens | List a | List b |
|---|---|---|---|
| 9 | Move One into b | Two | One |
| 10 | Move One back to the end of a | Two, One | (empty) |
| 11 | Remove Two | One | (empty) |
| 12–14 | Make Three and append it to b | One | Three |
Appending never copies: One is moved twice and ends up back in list a, after the place where Two was.
Reread 18.7 Creating, Adding, and Removing Elements if your answer differed.
18.8 CSS Classes and Attributes
A task app needs to show done tasks crossed out, urgent ones in red, and so on. You could change each element’s look from code, one property at a time, but the web has a better split: the look goes in a stylesheet, and the code only says which group an element belongs to.
CSS (Cascading Style Sheets) is the language of stylesheets. A CSS rule is a selector, the same kind as on querySelector, followed by settings in braces. To try it, first put this line back at the top of src/main.ts, above the example’s code, so Vite loads the stylesheet:
import "./style.css";
Then replace everything in src/style.css with:
.done {
text-decoration: line-through;
color: gray;
}
.late {
color: firebrick;
}
.highlight {
background-color: yellow;
}
The first rule says “every element with the class done gets a line through its text, in gray”. To cross a task out, the code now only has to add the class done to it.
Every element has a classList property for exactly that, with four methods:
| Method | What it does |
|---|---|
classList.add("done") |
Adds the class (more than one name is allowed); adding one that is there does nothing |
classList.remove("done") |
Removes the class if it is there |
classList.toggle("done") |
Adds it if missing, removes it if present, and gives back true if it is now present |
classList.contains("done") |
true if the element has the class |
Classes are one attribute. For any other attribute, elements have setAttribute(name, value), which sets the attribute name to the string value, adding it if it was not there, and getAttribute(name), which gives the value as a string, or null if the element has no such attribute. Attributes you will use include href (where a link goes), title (a tooltip), aria-label (a description that screen readers read aloud), and your own data attributes, any name starting with data-, for storing a small piece of information on an element.
Worked example: Marking tasks and finishing a link
<ul id="tasks">
<li>Water the plants</li>
<li class="urgent">Pay the phone bill</li>
</ul>
<a id="help">Help</a>const first = document.querySelector("li");
const bill = document.querySelector(".urgent");
const help = document.querySelector("#help");
if (first === null || bill === null || help === null) {
throw new Error("The page is missing an element");
}
first.classList.add("done");
bill.classList.remove("urgent");
bill.classList.add("late", "starred");
console.log(
first.classList.contains("done"),
bill.classList.contains("urgent"),
);
help.setAttribute("href", "https://example.com/help");
help.setAttribute("title", "Open the help page");
console.log(help.getAttribute("href"));
console.log(help.getAttribute("target"));true false
https://example.com/help
nullAfter the script, the body is:
<ul id="tasks">
<li class="done">Water the plants</li>
<li class="late starred">Pay the phone bill</li>
</ul>
<a id="help" href="https://example.com/help" title="Open the help page">Help</a>- Line 8: the first
ligains the classdone, so the stylesheet crosses it out. - Lines 9 and 10: the bill loses
urgentand gains two classes at once. Theclassattribute now lists both, separated by a space. - Lines 11 to 14:
containsconfirms both changes. - Lines 16 and 17: an
aelement only becomes a working link once it has anhref.setAttributeadds it, and atitle. - Lines 18 and 19: reading
hrefgives the string just set; reading an attribute that is not there givesnull, sogetAttributehas the typestring | null.
Now vary the method: toggle changes direction each time it is called, which makes it the natural fit for anything that switches on and off.
<p id="lamp">Desk lamp</p>const lamp = document.querySelector("#lamp");
if (lamp === null) {
throw new Error("No #lamp element on the page");
}
console.log(lamp.classList.toggle("on"));
console.log(lamp.classList.toggle("on"));
console.log(lamp.classList.toggle("on"));
lamp.setAttribute("aria-label", "Desk lamp, switched on");true
false
true
<p id="lamp" class="on" aria-label="Desk lamp, switched on">Desk lamp</p>
The first toggle adds on and gives back true, the second removes it and gives false, and the third adds it again. Line 9 adds an aria-label, so a screen reader announces the lamp’s state, which a color alone would not tell a blind user.
Watch out
Writing the dot in the class name. In a selector, .done means “the class done”. In classList, you pass the class name itself:
const bread = document.querySelector("#bread");
if (bread === null) {
throw new Error("No #bread element on the page");
}
bread.classList.add(".done");
console.log(bread.classList.contains("done"));false<li id="bread" class=".done">Bread</li>npx tsc accepts it, because ".done" is a string. The element now has a class literally named .done, which the .done rule in the stylesheet does not match, so nothing is crossed out, and contains("done") is false. Drop the dot: classList.add("done").
Key idea
Put the look in CSS rules and let code choose the class: classList.add, remove, toggle and contains manage an
element’s classes. setAttribute(name, value) sets any other attribute, and getAttribute(name) reads one as string | null.
Pause and try
Question 12 · Tracing
Predict exactly what the console shows and how the paragraph looks in the DOM afterwards.
<p id="card" class="card new">Ana Lee</p>const card = document.querySelector("#card");
if (card === null) {
throw new Error("No #card element on the page");
}
card.classList.remove("new");
card.classList.add("card");
const shown = card.classList.toggle("hidden");
card.classList.toggle("selected");
card.setAttribute("id", "player");
console.log(shown, card.classList.contains("new"));
console.log(document.querySelector("#card"));Check your reasoning
true false
null<p id="player" class="card hidden selected">Ana Lee</p>| Line | Classes after it | Note |
|---|---|---|
| 6 | card | new removed |
| 7 | card | already there, so nothing changes |
| 8 | card hidden | toggle added it, so shown is true |
| 9 | card hidden selected | added |
Line 10 changes the id itself to player, so on line 12 nothing has the id card any more, and querySelector gives null.
Reread 18.8 CSS Classes and Attributes if your answer differed.
18.9 Rendering a List from an Array
Real apps keep their data in arrays of objects, like Day 7’s and Day 10’s, and the page has to show that data. When the data changes, the page has to change with it. Updating the page by hand, one append or remove at a time, gets confusing fast: which items are already shown, and where should the new one go?
There is a simpler plan, and almost every web app uses some version of it. Write one function that takes the data and draws all of it, from nothing, every time:
- Empty the container. Assigning
list.textContent = ""replaces everything inside an element with no text at all, which removes all its children. - For each item in the array, create an element, fill it with
textContent, add classes, and append it.
Drawing the page from data like this is called rendering, and the function is a render function. Whenever the data changes, change the array and call the render function again. Because step 1 starts from empty, the page always matches the array exactly, however many times you render.
Worked example: A task list from an array
<h1>Today</h1>
<ul id="tasks"></ul>
<p id="summary"></p>interface Task {
title: string;
done: boolean;
}
function renderTasks(
tasks: Task[],
list: HTMLUListElement,
summary: HTMLElement,
): void {
list.textContent = "";
for (const task of tasks) {
const item = document.createElement("li");
item.textContent = task.title;
if (task.done) {
item.classList.add("done");
}
list.append(item);
}
const left = tasks.filter((task) => !task.done).length;
summary.textContent = `${left} of ${tasks.length} left`;
}
const tasks: Task[] = [
{ title: "Water the plants", done: true },
{ title: "Pay the phone bill", done: false },
{ title: "Call Grandma", done: false },
];
const list = document.querySelector<HTMLUListElement>("#tasks");
const summary = document.querySelector<HTMLParagraphElement>("#summary");
if (list === null || summary === null) {
throw new Error("The page is missing an element");
}
renderTasks(tasks, list, summary);
tasks.push({ title: "Book the dentist", done: false });
renderTasks(tasks, list, summary);After the script, the body is:
<h1>Today</h1>
<ul id="tasks">
<li class="done">Water the plants</li>
<li>Pay the phone bill</li>
<li>Call Grandma</li>
<li>Book the dentist</li>
</ul>
<p id="summary">3 of 4 left</p>- Lines 1 to 4: Day 10’s interface describes one task.
- Line 11: empty the list.
- Lines 12 to 19: one
liper task, crossed out with the classdonewhen the task is done. - Lines 20 and 21: Day 11’s
filtercounts the tasks still to do, and the summary shows it. - Lines 30 to 34: find the two elements and narrow them, once.
- Line 36: the first render draws three tasks. Line 37 changes the data, not the page. Line 38 renders again: the list is emptied and redrawn with four tasks, and the summary goes from “2 of 3 left” to “3 of 4 left”. No task is shown twice.
Notice that renderTasks receives the list and the summary as parameters, typed HTMLUListElement and HTMLElement with no | null. The narrowing happens once, outside, and the function never has to think about missing elements. That is not only tidy; it is what the checker needs, as the Watch Out below shows.
Now vary the data: an empty array. A blank list looks broken, so a good render function says so. This version builds each item with a small helper function and Day 11’s map, then adds them all with one append and Day 10’s spread:
<ul id="tasks">
<li>Old task from the HTML</li>
</ul>function makeItem(title: string): HTMLLIElement {
const item = document.createElement("li");
item.textContent = title;
return item;
}
function renderTitles(titles: string[], list: HTMLUListElement): void {
list.textContent = "";
if (titles.length === 0) {
const empty = makeItem("Nothing to do. Enjoy your day!");
empty.classList.add("empty");
list.append(empty);
return;
}
list.append(...titles.map(makeItem));
}
const list = document.querySelector<HTMLUListElement>("#tasks");
if (list === null) {
throw new Error("No #tasks list on the page");
}
renderTitles(["Bike ride", "Bake bread"], list);
console.log(list.children.length);
renderTitles([], list);
console.log(list.children.length);2
1
<ul id="tasks">
<li class="empty">Nothing to do. Enjoy your day!</li>
</ul>
- Line 8: emptying the list also removes the “Old task” item that came with the HTML. After the first render, the page shows only the array’s data.
- Line 15:
titles.map(makeItem)turns astring[]into anHTMLLIElement[];...passes each element as its own argument, andappendadds them all, in order. Line 24 shows 2. - Lines 9 to 14: with an empty array, the function appends a single message item instead and returns early, as on Day 8. Line 26 shows 1.
Watch out
Narrowing outside a function, using the element inside it. It is natural to write the render function with no parameters and use the narrowed list directly:
const list = document.querySelector<HTMLUListElement>("#tasks");
if (list === null) {
throw new Error("No #tasks list on the page");
}
function renderTitles(titles: string[]): void {
list.textContent = "";
for (const title of titles) {
const item = document.createElement("li");
item.textContent = title;
list.append(item);
}
}
renderTitles(["Bike ride", "Bake bread"]);npx tsc reports:
render-unnarrowed.dom.ts:7:3 - error TS18047: 'list' is possibly 'null'.
render-unnarrowed.dom.ts:11:5 - error TS18047: 'list' is possibly 'null'.The if on line 2 did narrow list, but only for the code that runs after it. A function declared with function can be called from anywhere in the file, even from a line above the if, before the check has happened, so inside its body the checker goes back to the declared type, HTMLUListElement | null. Pass the element in as a parameter, as renderTasks does: then the caller must hand over a real HTMLUListElement, and the narrowing at the call site is what proves it.
Key idea
A render function empties its container and redraws it from the data: one created element per item, with textContent
and classes, appended in order. Change the array, then render again. Pass the narrowed elements to the function as
parameters.
Pause and try
Question 13 · Multiple choice
A render function starts with list.textContent = "";. What would happen if that line were deleted and the function were called twice?
- Nothing different:
appendreplaces items that are already there npx tscwould report thatlistis possibly not empty- The second call would add every item again after the first call’s items, so the list would show the early items twice
- The second call would crash, because an element cannot be appended twice
Check your reasoning
C. append always adds to the end. Without emptying the list first, the second render draws the whole array again below what the first render left, so the items from the first call appear twice.
- A is wrong:
appendnever replaces anything. (It moves an element that is already in the tree, but each render makes brand-new elements, so there is nothing to move.) - B is wrong: the checker knows nothing about what a list contains at runtime.
- D is wrong: each call creates new elements, and even appending the same element twice only moves it.
Reread 18.9 Rendering a List from an Array if you chose differently.
Putting it together
A reading tracker shows a shelf of books from an array: a heading with the count, one list item per book with the title in bold, finished books marked with a class, and a line of progress underneath. To try it, add a .finished rule to style.css, for example .finished { color: green; }.
<h1 id="heading">My books</h1>
<ul id="books"></ul>
<p id="progress"></p>interface Book {
title: string;
author: string;
pages: number;
finished: boolean;
}
function makeBookItem(book: Book): HTMLLIElement {
const item = document.createElement("li");
const title = document.createElement("strong");
title.textContent = book.title;
item.append(title, ` by ${book.author}, ${book.pages} pages`);
item.setAttribute("data-pages", String(book.pages));
if (book.finished) {
item.classList.add("finished");
}
return item;
}
function renderShelf(
books: Book[],
heading: HTMLElement,
list: HTMLUListElement,
progress: HTMLElement,
): void {
heading.textContent = `My books (${books.length})`;
list.textContent = "";
list.append(...books.map(makeBookItem));
const done = books.filter((book) => book.finished);
const pagesRead = done.reduce((total, book) => total + book.pages, 0);
progress.textContent = `Finished ${done.length}, ${pagesRead} pages read`;
}
const books: Book[] = [
{ title: "Hatchet", author: "Gary Paulsen", pages: 195, finished: true },
{ title: "Wonder", author: "R. J. Palacio", pages: 310, finished: false },
{ title: "Holes", author: "Louis Sachar", pages: 233, finished: true },
];
const heading = document.querySelector<HTMLHeadingElement>("#heading");
const list = document.querySelector<HTMLUListElement>("#books");
const progress = document.querySelector<HTMLParagraphElement>("#progress");
if (heading === null || list === null || progress === null) {
throw new Error("The page is missing an element");
}
renderShelf(books, heading, list, progress);npx tsc reports no errors, and after the script the body is:
<h1 id="heading">My books (3)</h1>
<ul id="books">
<li data-pages="195" class="finished"><strong>Hatchet</strong> by Gary Paulsen, 195 pages</li>
<li data-pages="310"><strong>Wonder</strong> by R. J. Palacio, 310 pages</li>
<li data-pages="233" class="finished"><strong>Holes</strong> by Louis Sachar, 233 pages</li>
</ul>
<p id="progress">Finished 2, 428 pages read</p>
Follow the data through the program:
| Lines | What happens | Idea |
|---|---|---|
| 1–6 | The Book interface describes the data |
18.9 |
| 9–11 | Two new elements; the title goes into the strong with textContent, never innerHTML |
18.6, 18.7 |
| 12 | append with an element and a string: the bold title, then plain text after it |
18.7 |
| 13 | A data attribute keeps each book’s page count on its element; the value must be a string | 18.8 |
| 14–16 | Finished books get the class the stylesheet colors | 18.8 |
| 26–28 | Render: set the heading, empty the list, append one item per book with map and spread |
18.9 |
| 29–31 | filter and Day 11’s reduce work out the progress line from the same data |
18.9 |
| 40–45 | The generic form gives each element its specific type, and one if narrows all three |
18.4, 18.5 |
| 47 | The narrowed elements go into the render function as parameters | 18.9 |
Try changing the data: mark Wonder as finished, or add a fourth book, and save. The page redraws with the new count, the new item and the new total, because every number on it comes from the array.
Common mistakes
| Message or symptom | Usual cause | Fix |
|---|---|---|
TS18047: 'title' is possibly 'null'. |
Using querySelector’s result without narrowing |
if (title === null) { throw new Error(…); } |
TS18047 inside a function, though the element was narrowed above it |
Narrowing does not reach into a function declaration |
Pass the element in as a parameter |
TS2339: Property 'value' does not exist on type 'Element'. |
An id or class selector gives the general Element type |
querySelector<HTMLInputElement>(…) or instanceof |
undefined where a value should be, and no type error |
The generic form promised the wrong kind of element | Check the HTML, or use instanceof |
The page works but npx tsc reports errors |
Vite strips types without checking them | Run npx tsc after every change |
| A created element never appears | createElement without append |
Append it to an element in the tree |
| Items appear twice after a second render | The render function does not empty the container first | Start with list.textContent = "" |
| A class has no effect | classList.add(".done") with the dot |
classList.add("done") |
| Tags in user text become real elements | User text assigned to innerHTML |
Use textContent |
Vocabulary
| Term | Definition | Example |
|---|---|---|
| Vite | A tool that creates browser projects and serves them during development | npm create vite@latest day18 |
| development server | A program on your computer that serves your page to the browser and reloads it on save | npm run dev |
| template | A ready-made starting project | --template vanilla-ts |
| localhost | The name a computer uses for itself | http://localhost:5173/ |
| HTML | The language web pages are written in | <h1>My tasks</h1> |
| tag | A name in angle brackets that marks where an element starts or ends | <li>, </li> |
| element | One piece of a page: an opening tag, its content, and a closing tag | <p>Hello</p> |
| attribute | A name="value" setting in an opening tag |
id="tasks" |
id |
An attribute giving one element a unique name | <ul id="tasks"> |
class |
An attribute giving an element group labels that many elements can share | <li class="done"> |
| console | The browser panel where console.log output and errors appear |
F12, then Console |
| DOM | The tree of objects the browser builds from the HTML, which code reads and changes | document.body |
| tree | A structure where every item except the top one sits inside exactly one other | ul holding lis |
| child / parent / sibling | An element directly inside another / the element it is in / elements with the same parent | li / ul / two lis |
| text node | The text inside an element, stored as its own item in the tree | "Bike ride" in an li |
| selector | A string describing which elements to match | "#tasks li" |
Element |
The type of any element, with the properties all elements share | Element | null from querySelector |
innerHTML |
An element’s content as HTML; assigning it builds elements from the string | box.innerHTML = "<b>hi</b>" |
textContent |
An element’s text; assigning it shows the string as plain text | title.textContent = "Hi" |
| cross-site scripting | An attack where someone else’s text runs as code on your page | a comment with an onerror attribute in innerHTML |
| CSS | The language of stylesheets, which set how elements look | .done { color: gray; } |
| rule | A CSS selector followed by settings in braces | .late { color: firebrick; } |
| data attribute | An attribute whose name starts with data-, for storing your own information on an element |
data-pages="195" |
| rendering | Drawing the page from data | renderTasks(tasks, list, summary) |
| render function | A function that empties a container and redraws it from data | renderTasks |
Summary
npm create vite@latestmakes a browser project andnpm run devserves it, reloading on every save.index.html’s<script type="module" src="/src/main.ts">makes the browser fetchmain.ts, with its types stripped, and run it after the page has been read. Vite never checks types, so keep runningnpx tsc.- The browser turns the HTML into the DOM, a live tree of element objects starting at
document; changing the tree changes the page. document.querySelector(selector)gives the first match ornull, typedElement | null. Narrow it before use. For specific properties such asvalue, use a tag selector, the generic formquerySelector<HTMLInputElement>(…)(a promise the checker trusts), orinstanceof(checked by the browser).createElementmakes an element,appendadds or moves elements and text,removetakes them away,classListmanages classes for CSS, andsetAttributesets other attributes. Text from anyone else goes intextContent, neverinnerHTML.- A render function empties its container and redraws it from an array; change the data, then render again, passing narrowed elements in as parameters.
Practice
Do these in your day18 project with npm run dev running. For each one, put the page in index.html, the script in src/main.ts (with import "./style.css"; at the top), check with npx tsc in your second terminal, and look at the page and at the Elements tab of the developer tools. Only then open the answer. Then change the array and save, and check that the page follows.
Question 14 · Short answer
A task list. Store an array of task titles in your script. Render it as a <ul>, one <li> per task, into an empty list in the HTML, and log how many tasks are shown.
Check your reasoning
One possible solution:
<h1>My tasks</h1>
<ul id="tasks"></ul>const tasks = ["Water the plants", "Pay the phone bill", "Call Grandma"];
const list = document.querySelector<HTMLUListElement>("#tasks");
if (list === null) {
throw new Error("No #tasks list on the page");
}
for (const task of tasks) {
const item = document.createElement("li");
item.textContent = task;
list.append(item);
}
console.log(`${list.children.length} tasks shown`);3 tasks shown<h1>My tasks</h1>
<ul id="tasks">
<li>Water the plants</li>
<li>Pay the phone bill</li>
<li>Call Grandma</li>
</ul>Line 3 finds the list with the generic form, and lines 4 to 6 narrow it. The loop makes one li per title, fills it with textContent, and appends it, so the items appear in array order. Line 13 counts the list’s children. Try adding a fourth task, and try an empty array: the list is blank, which is why the next exercises use a render function with an empty message.
Reread 18.7 Creating, Adding, and Removing Elements and 18.9 Rendering a List from an Array if your result differed.
Question 15 · Short answer
Highlight a word. Render a list of task titles, and add the CSS class highlight to every task whose title contains a given word, ignoring capital letters. Add a .highlight rule to your stylesheet so the matches stand out.
Check your reasoning
One possible solution, with the .highlight rule from 18.8 in style.css:
<h1>My tasks</h1>
<ul id="tasks"></ul>function renderHighlighted(
tasks: string[],
word: string,
list: HTMLUListElement,
): void {
list.textContent = "";
const target = word.toLowerCase();
for (const task of tasks) {
const item = document.createElement("li");
item.textContent = task;
if (task.toLowerCase().includes(target)) {
item.classList.add("highlight");
}
list.append(item);
}
}
const tasks = [
"Buy milk",
"Return library books",
"Milk the goat",
"Call Grandma",
];
const list = document.querySelector<HTMLUListElement>("#tasks");
if (list === null) {
throw new Error("No #tasks list on the page");
}
renderHighlighted(tasks, "milk", list);<h1>My tasks</h1>
<ul id="tasks">
<li class="highlight">Buy milk</li>
<li>Return library books</li>
<li class="highlight">Milk the goat</li>
<li>Call Grandma</li>
</ul>renderHighlighted is a render function that takes the word as a parameter. Line 7 lowers the word once; line 11 lowers each title and uses Day 3’s includes, so “Milk the goat” matches “milk” despite its capital. Only the matching items get the class, and the stylesheet does the rest. Call it again with "call" and only Call Grandma is highlighted, because the list is emptied first.
Reread 18.8 CSS Classes and Attributes if your result differed.
Question 16 · Short answer
A product table. Store an array of products, each with a name, a price and a stock count. Build a <table> with a heading row (Product, Price, In stock) and one row per product, prices shown with two decimal places, and append it to an empty <div id="app">. Mark any product with no stock with the class sold-out.
Check your reasoning
One possible solution:
<h1>Price list</h1>
<div id="app"></div>interface Product {
name: string;
price: number;
stock: number;
}
function makeCell(tag: "th" | "td", text: string): HTMLTableCellElement {
const cell = document.createElement(tag);
cell.textContent = text;
return cell;
}
function makeTable(products: Product[]): HTMLTableElement {
const table = document.createElement("table");
const head = document.createElement("thead");
const headRow = document.createElement("tr");
headRow.append(
makeCell("th", "Product"),
makeCell("th", "Price"),
makeCell("th", "In stock"),
);
head.append(headRow);
const body = document.createElement("tbody");
for (const product of products) {
const row = document.createElement("tr");
row.append(
makeCell("td", product.name),
makeCell("td", `$${product.price.toFixed(2)}`),
makeCell("td", String(product.stock)),
);
if (product.stock === 0) {
row.classList.add("sold-out");
}
body.append(row);
}
table.append(head, body);
return table;
}
const products: Product[] = [
{ name: "Pencil", price: 0.5, stock: 120 },
{ name: "Notebook", price: 3.25, stock: 0 },
{ name: "Backpack", price: 24, stock: 7 },
];
const app = document.querySelector("#app");
if (app === null) {
throw new Error("No #app element on the page");
}
app.append(makeTable(products));<h1>Price list</h1>
<div id="app">
<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>In stock</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pencil</td>
<td>$0.50</td>
<td>120</td>
</tr>
<tr class="sold-out">
<td>Notebook</td>
<td>$3.25</td>
<td>0</td>
</tr>
<tr>
<td>Backpack</td>
<td>$24.00</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>A table is a tree several levels deep: table holds thead (the heading section) and tbody (the body section), each holds tr rows, and each row holds th or td cells. makeCell takes Day 9’s literal union "th" | "td", so it can only make the two kinds of cell, and createElement gives both the type HTMLTableCellElement. makeTable builds the whole table while it is still off the page, and line 51 appends it in one step. Line 29 uses Day 3’s toFixed(2), and the extra $ before ${ is a plain dollar sign. Add a .sold-out { color: gray; } rule to see the class.
Reread 18.7 Creating, Adding, and Removing Elements if your result differed.
Review questions
Question 17 · Tracing
Predict exactly what the console shows and what the menu holds afterwards.
<ul id="menu">
<li>Soup</li>
</ul>interface Dish {
name: string;
vegan: boolean;
}
function renderMenu(dishes: Dish[], menu: HTMLUListElement): void {
menu.textContent = "";
for (const dish of dishes) {
if (dish.name.length > 5) {
continue;
}
const item = document.createElement("li");
item.textContent = dish.name;
if (dish.vegan) {
item.classList.add("vegan");
}
menu.append(item);
}
}
const dishes: Dish[] = [
{ name: "Salad", vegan: true },
{ name: "Lasagna", vegan: false },
{ name: "Tacos", vegan: false },
];
const menu = document.querySelector<HTMLUListElement>("#menu");
if (menu === null) {
throw new Error("No #menu list on the page");
}
renderMenu(dishes, menu);
dishes.push({ name: "Curry", vegan: true });
console.log(menu.children.length);Check your reasoning
2<ul id="menu">
<li class="vegan">Salad</li>
<li>Tacos</li>
</ul>- Line 7 empties the menu, so Soup from the HTML is gone.
- Lines 9 to 11: Day 5’s
continueskips any dish whose name is longer than 5 letters, so Lasagna (7) is never drawn. - Salad is vegan and gets the class; Tacos does not.
- Line 32 adds Curry to the array, but nothing renders again, so the page does not change: the menu still has 2 items. The page only follows the data when the render function runs.
Reread 18.9 Rendering a List from an Array if your answer differed.
Question 18 · Debugging
This script should show the scores 12, 18 and 25 after the second render. npx tsc accepts it, but the list is wrong. Predict what the list shows, explain why, and fix it.
function renderScores(scores: number[], list: HTMLUListElement): void {
for (const score of scores) {
const item = document.createElement("li");
item.textContent = String(score);
list.append(item);
}
}
const scores = [12, 18];
const list = document.querySelector<HTMLUListElement>("#scores");
if (list === null) {
throw new Error("No #scores list on the page");
}
renderScores(scores, list);
scores.push(25);
renderScores(scores, list);Check your reasoning
The list shows five items: 12, 18, 12, 18, 25. The first render appends 12 and 18. The second render appends all three scores again after them, because nothing empties the list first, and append always adds to the end. Nothing complains, because appending is allowed. Empty the list at the start of the render function:
function renderScores(scores: number[], list: HTMLUListElement): void {
list.textContent = "";
for (const score of scores) {
const item = document.createElement("li");
item.textContent = String(score);
list.append(item);
}
}
const scores = [12, 18];
const list = document.querySelector<HTMLUListElement>("#scores");
if (list === null) {
throw new Error("No #scores list on the page");
}
renderScores(scores, list);
scores.push(25);
renderScores(scores, list);<ul id="scores">
<li>12</li>
<li>18</li>
<li>25</li>
</ul>Reread 18.9 Rendering a List from an Array if you missed it.
Question 19 · Debugging
This should grey out the Save button. npx tsc reports two errors on line 2. Explain each one and write a fixed version.
const saveButton = document.querySelector("#save");
saveButton.disabled = true;disable-save.dom.ts:2:1 - error TS18047: 'saveButton' is possibly 'null'.
disable-save.dom.ts:2:12 - error TS2339: Property 'disabled' does not exist on type 'Element'.Check your reasoning
- TS18047 (column 1):
querySelectorgivesElement | null, and nothing narrowed away thenull. - TS2339 (column 12): with an id selector, the checker only knows
saveButtonis anElement, anddisabledbelongs toHTMLButtonElement.
The generic form fixes the second, and a throw fixes the first:
const saveButton = document.querySelector<HTMLButtonElement>("#save");
if (saveButton === null) {
throw new Error("No #save button on the page");
}
saveButton.disabled = true;On a page with <button id="save" type="button">Save</button>, the button becomes:
<button id="save" type="button" disabled="">Save</button>if (!(saveButton instanceof HTMLButtonElement)) { throw … } would fix both errors at once, and also check at runtime that #save really is a button.
Reread 18.4 Finding Elements with querySelector and 18.5 Element Types and the Generic Form if you missed either.
Question 20 · Short answer
You run npm run dev, open the address, and see “Welcome back, Ana” in the heading of a page whose index.html says <h1 id="title">Hello</h1>. Describe, in order, every step between opening the address and seeing that text, and say why the Elements tab shows “Welcome back, Ana” although index.html still says “Hello”.
Check your reasoning
Model answer: The browser asks Vite’s server for the page and gets index.html. It reads the HTML and builds the DOM tree, including the h1 with the text “Hello”. It finds the <script type="module" src="/src/main.ts"> tag and asks Vite for main.ts; Vite strips the types and sends JavaScript. After the whole page has been read, the browser runs the script, which finds the h1 with querySelector("#title"), narrows it, and assigns its textContent. The DOM changes, and the browser redraws the heading. The Elements tab shows the DOM as it is now, not the original file, so it shows “Welcome back, Ana”; index.html itself is never changed.
A complete answer includes: Vite serves the page and the stripped script; the browser builds the DOM from the HTML; the module script runs after the page is read; the script changes the DOM, not the file.
Reread 18.2 How the Page Loads Your Script and 18.3 The DOM as a Tree if your answer differed.
Question 21 · Multiple choice
list is a narrowed HTMLUListElement holding three lis. Which line leaves the ul on the page with no items in it?
list.remove();list.textContent = "";list.classList.remove("li");list.innerHTML = "<li></li>";
Check your reasoning
B. Assigning an empty string to textContent replaces everything inside the list with no text, so all three lis are gone and the empty ul stays. It is how a render function starts.
- A is wrong:
removetakes theulitself off the page, with everything inside it. - C is wrong:
classList.removeremoves a class namedlifrom the list’sclassattribute; it does not touch the list’s children. - D is wrong: it replaces the three items with one new, empty
li, so the list is not empty.
Reread 18.9 Rendering a List from an Array and 18.8 CSS Classes and Attributes if you chose differently.
Go further
MDN’s introduction explains the DOM tree and how scripts reach it, and its “Manipulating documents” page goes on to creating, moving and styling elements: MDN: Introduction to the DOM and MDN: Manipulating documents. Vite’s own guide covers everything npm create vite@latest sets up: Vite: Getting Started.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can create a Vite project, start it with npm run dev, and say why I still run npx tsc. Reread
- I can read a small HTML page and explain how its script tag loads main.ts. Reread
- I can draw the DOM tree for a small page and name parents, children and siblings. Reread
- I can find an element with a selector and narrow the Element | null that querySelector gives. Reread
- I can get a specific element type with a tag selector, the generic form, or instanceof, and say which one is checked at runtime. Reread
- I can explain why text from users goes in textContent and never innerHTML. Reread
- I can create, append, move and remove elements. Reread
- I can change an element’s classes with classList and its attributes with setAttribute. Reread
- I can write a render function that draws a list from an array and can be called again. Reread