In lesson 2.2.1, your first script counted the rows of the contact list. Now the list gets something that really helps people in the office: a search that filters as you type. For that, a script has to read the page, react to input and change the page. All of this happens through the DOM.
The order stays the one from lesson 2.2.1: First the page gets a search form that works without script. Then the script comes in and makes the search faster. Along the way you learn three rules that apply to every script in the Kladde: Elements are checked, not claimed. Text gets onto the page only as text. And whatever changes is also heard by people who can’t see the page.
The DOM: the page as a tree
The browser reads the HTML the server sends and builds a tree of objects from it: the Document Object Model, DOM for short. Every
element becomes an object with properties and methods, every text a text node, and at the very top stands document. For the start of
the contact list, the tree looks like this:
document
└── html (lang="en")
├── head
│ ├── meta …
│ ├── title "Contacts – Kladde"
│ └── script (type="module") …
└── body
├── header …
├── main
│ ├── h1 "Contacts"
│ ├── p "Four contacts, sorted by name."
│ └── table (id="contacts")
│ ├── caption "The office’s contacts"
│ ├── thead …
│ └── tbody
│ ├── tr
│ │ ├── th "Bernd Example"
│ │ ├── td "Example Corp."
│ │ └── td
│ │ └── a (href="mailto:…") "bernd@example.org"
│ └── tr …
└── footer …
A script never changes the HTML, always the DOM. You can see that in the browser tools from lesson 2.1.5: The Elements tab shows the DOM as it is right now, with everything a script changed. The page source (Ctrl+U) shows the HTML as it came from the server. After your script from lesson 2.2.1, Elements says “4 contacts, sorted by name.” while the page source still says “Four contacts”.
The console of the browser tools is a good place to try things. Open the Kladde’s contact list and the console, and type:
document.querySelectorAll("tr").length
5
Five rows: one in the head of the table, four in the body. What you type in the console is JavaScript without types, and it disappears when you reload. For scripts that are supposed to stay, you write TypeScript.