Unit 6 · JavaScript in the page
Why querySelector returns null
The script ran before the browser had built that element, so there was nothing to find. Move the <script> below the element (or to the end of the body), use defer, or wait for DOMContentLoaded.
The mix-up
What people often think
“Adding a delay is the right fix.”
What the tutor says
A delay is a guess that can fail on a slow phone. Move the script below the element, or wait for DOMContentLoaded.
How it works
The browser reads HTML top to bottom and runs a plain script the moment it reaches it. A script in the head that looks for a button further down finds null, and the next line throws “Cannot read properties of null”.
A setTimeout delay is a guess that fails on a slow phone, and deleting the script removes the feature along with the error. Change when the script runs instead.
Side by side
<head>
<script src="app.js"></script>
</head>
<body>
<p id="status"></p>
</body><head>
<script src="app.js" defer></script>
</head>
<body>
<p id="status"></p>
</body>Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Removing the script fixes the error.”
The error goes away, but so does the feature. Leave the script in and change when it runs.
“Typing "Open now" into the HTML is the same thing.”
That hides the bug. The point is that code can change the page, so make the script work.
Practise it with a tutor watching
Select and change
Find any element on a page with code and change its text and style.
Free, no account needed.