querySelector returns null
Locate the failed assumption, reproduce it, then repair the cause.
What actually caused it
The selector did not match a node that exists at the moment the query runs. The next read then throws, often as a failure to read a property of . The name in the selector is not the bug by itself. Either the document never contained that element, or the script ran before the parser created it.
A class of nav on a div does not create a nav element. A component that renders the node only after a condition can also miss. Logging the parent element and reading the Elements panel at the same moment as the query shows whether the node is absent or merely not yet parsed.
This is different from a CSS rule that fails to match. The query is about the tree of elements. The Styles pane is about declarations on an element you already found.
Minimal reproduction
A class standing in for an element
const nav = document.querySelector("nav");
console.log(nav.tagName);The markup is a div with class nav, so the query is .
The markup the query expected
<div class="nav">
<a href="#notes">Notes</a>
</div>Nothing here is a nav element.
The fix
Match the selector to the element that is actually in the HTML, or change the HTML to the element you meant. If the node is created later, run the query after parsing, for example from a defer script or after the markup it needs.
Do not guard every query with an empty catch and continue. A missing landmark or control is usually a broken contract. Check it, report it, and fix the markup. In DevTools, use the Elements panel search for the selector before you change the script.
Use the element the landmark requires
<nav>
<a href="#notes">Notes</a>
</nav>Read it after it exists
const nav = document.querySelector("nav");
if (nav === null) {
console.error("Expected a nav landmark");
} else {
console.log(nav.tagName);
}