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.
Topics in This Chapter
querySelector and querySelectorAll find elements with the CSS selectors you already know, and null is what comes back when nothing matches.textContent and innerHTML, the injection that the wrong one lets in, and the one rule for choosing between them.classList, reading and setting attributes, and your own data- values read through dataset.createElement, template and replaceChildren: the site's project cards built from an array instead of written by hand.