TypeError: Cannot set properties of null (setting 'x')
Locate the failed assumption, reproduce it, then repair the cause.
What actually caused it
The value on the left of .x is , so there is no to receive the assignment. With code, a selector commonly returned null because its selector was wrong, the node was removed, or the script ran before the element existed.
The message names the you tried to set. With element.textContent, it will normally say setting 'textContent' rather than 'x'. The underlying cause is the same missing element.
Inspect both timing and spelling. A -ready handler cannot fix a selector that never matches, and a correct selector cannot find a node that has not been created yet.
Minimal reproduction
Assigning through a missing match
const element = document.querySelector("#missing-panel");
element.x = 1;This reproduces the exact name in the title.
A script before its target
<script>
document.querySelector("#status").textContent = "Ready";
</script>
<p id="status"></p>The paragraph has not been parsed when this script runs.
The fix
Run -dependent work after its required elements exist. A deferred external script, a script, or an appropriate DOMContentLoaded handler can provide that ordering. If setup may run after DOMContentLoaded has already fired, inspect document.readyState before subscribing.
Check the selection as well. If the element is optional, return deliberately. If it is required, report the missing selector so a broken page does not fail silently. Optional chaining cannot be used as the assignment target for this repair.
Handle both timing and the selector
function setup() {
const status = document.querySelector("#status");
if (!status) {
console.error("Required #status element is missing");
return;
}
status.textContent = "Ready";
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", setup, { once: true });
} else {
setup();
}Use this with a page that contains an element whose id is status.