Understand the idea
The Document Object Model represents the parsed page as objects. querySelector finds the first element matching a CSS selector.
A query returns null if no matching element exists at that moment. A deferred external script runs after HTML parsing, making it useful for code that needs elements from the page. textContent replaces text without treating the value as HTML markup. An invalid selector throws a SyntaxError rather than returning null. For a classic external script, defer waits until parsing finishes; defer has no effect on an inline classic script. Module scripts defer by default unless async is used.
Read the example
This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.
// Run after an element with id="status" exists.
const statusElement = document.querySelector("#status");
if (statusElement) {
statusElement.textContent = "Ready to explore.";
}A small mistake, explained
What goes wrong
Calling a property on null produces an error. The selector may be wrong, or the script may run before the element exists.
How to fix it. Check the spelling and timing. Use defer on the external script element and verify whether the element is expected on this page.
Try it yourself
Add <p id="status">Loading</p> to a page. Run the snippet in its console and then test a misspelled selector.
Further reading
Keep exploring
- JavaScript · Guide
Variables & valuesGive a value a name and understand when it can change.
- JavaScript · Guide
Conditions & comparisonsMake a decision without accidentally changing the value.