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.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

querySelector found each element by its selector: # for the id and . for the class. Reading title.textContent printed the heading's words to the console, and assigning to note.textContent replaced the paragraph's words on the page.

YOUR TURN · WEB PAGE
Your turn → Add a paragraph to the HTML with the id goal, select it in JavaScript, and set its text to what you want to build after this course. Then misspell the id in your selector, run it, and read the error that appears.
loading editor…

Syntax has to be exact. Every quote, bracket, brace and parenthesis needs its partner, and every HTML tag you open needs closing. One slip and the script won't run; the message under the page will say where.

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.

◈ Graded Build

The visitor's name is in a variable. Using JavaScript only, change the heading to say Welcome, followed by a comma, a space and the visitor's name, and fill the empty paragraph with the words Made with JavaScript. Build the heading from the variable rather than typing the name.

Checked by using your page: clicking, typing and waiting, then reading what changed. 2 visible and 1 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Changing How Things Look and Behave →
← Back