How JavaScript Reaches the Page
Until now your programs have talked through the console. Real applications change what is on the screen: a clock that ticks, a button that says Paused, a list that grows.
When the browser reads your HTML it builds the DOM, the Document Object Model: every element becomes an object, and JavaScript reaches all of them through one object called document. Change an object and the browser redraws that part of the page.
document.querySelector(selector) finds the first element that matches a CSS selector, the same selectors you used in HTML & CSS: #title for an id, .note for a class, li for a tag. It hands back the element, or null when nothing matches.
Once you have an element, textContent is its text. Read it to see what the page says; assign to it to change what the page says.
Where the script goes matters. The browser reads a page from top to bottom and runs each script the moment it reaches it. A script in the <head> runs before the body has been read, so the elements it looks for don't exist yet and querySelector returns null.
There are two fixes. Put <script src="script.js"></script> just before </body>, or keep it in the head and add defer, which tells the browser to wait until the page has been read. The lessons in this level run your script at the end of the body for you.
✦ Cannot read properties of null
This is the most common error in browser JavaScript, and it nearly always means querySelector found nothing. Check three things: the id or class is spelled exactly the same in the HTML and the selector, the selector has its # or . in front, and the script runs after the element exists.
Mark this lesson complete
Signed in, your progress follows you to every device.