Chapter Eight · Behaviour

The DOM: JavaScript Meets the Page

Where JavaScript reaches the page: the tree of objects the browser builds from your HTML, how a script finds an element in it, how to change text without letting an attacker's code in, how to switch the look with a class, and how to build the site's project cards from data.

Chapters 6 and 7 taught a language, but a script that only writes to the Console changes nothing a visitor can see. This chapter connects JavaScript to the page. The browser turns your HTML into a tree of objects called the DOM, and every change a script makes, from one word of text to a whole grid of cards, is a change to that tree. The screen follows. The file on disk never changes.

Five topics. The first shows the DOM as a tree and why it differs from your file. The second finds elements with CSS selectors and explains the null that comes back when nothing matches. The third changes text safely, and meets on purpose the injection that the wrong method lets in. The fourth switches the look with a class and carries information in attributes. The fifth builds the site's project cards from an array, so the Projects page is drawn from data instead of written by hand.

Every DOM change follows the same path
Find an elementor make a new one
→
Read or change ittext, class, attribute
→
The browser redrawsonly what changed
→
The visitor sees the changeuntil the page reloads

Topics in This Chapter