01 / 21
</>

DOM Pitfalls
Null Selectors & Timing

Master the most common DOM errors that trip up JavaScript developers: null references, race conditions, and timing bugs that silently break your code.

JavaScript

What Is the DOM?

The Document Object Model is a tree-shaped representation of your HTML that JavaScript uses to read and modify the page. Every element, attribute, and text node lives in this tree.

document <html> <head> <body> <div> <p> The DOM tree: a live, mutable data structure

How Selectors Find Elements

Methods like querySelector and getElementById search the DOM tree for a matching node. If the element exists, you get a reference. If it doesn't exist, you get null.

✓ Element found
Returns a live DOM node object. You can read properties, attach events, and modify it.
✕ Element missing
Returns null. Any property access on null throws a TypeError and halts your script.
// Returns a node or null const btn = document.querySelector('.submit-btn'); // If btn is null, this line crashes! btn.addEventListener('click', handler);

The Null Selector Problem

A null selector error happens when your JavaScript tries to use an element that the DOM hasn't created yet, or that simply doesn't exist. This is the single most common DOM bug.

HTML Parsing Script Runs Remaining HTML <button> created null returned! Script tries to find <button> before it exists in the DOM

The Core Timing Rule

This is not a bug in JavaScript: it is how the browser's parsing pipeline works. Understanding this single rule prevents the majority of DOM errors.

Parsing order
Browser reads HTML sequentially. Each tag becomes a DOM node in order.
Script blocking
A <script> tag pauses HTML parsing, runs immediately, then resumes.
Implication
Scripts in <head> cannot see <body> elements. They haven't been created yet.

DOMContentLoaded vs load

The browser fires two key events that signal readiness. Choosing the right one determines when your code can safely touch the DOM.

DOMContentLoaded window.onload
Fires when HTML fully parsed, DOM tree built All resources loaded (images, fonts, CSS)
Use for DOM manipulation Image dimensions, layout
Speed Fast: fires early Slow: waits for everything
Selectors safe? ✓ Yes ✓ Yes

Three Safe Patterns

1
Place scripts at the bottom of <body>. By the time the browser reaches your <script> tag, all HTML above it has been parsed.
2
Use the defer attribute. Adding defer to a <script> tag tells the browser: "Download now, execute after the DOM is ready."
3
Wrap code in DOMContentLoaded. This event fires once the entire DOM tree is constructed, guaranteeing all elements exist.

defer vs async

Both attributes change how a script loads and executes. They look similar but have very different timing guarantees.

default defer async Parse Blocked Exec Parse Parse (uninterrupted) Download (parallel) Exec Parse Download Exec Parse defer guarantees DOM-ready execution; async does not

Null-Safety Checklist

1
Check your script placement. Is your <script> before or after the elements it targets?
2
Verify selector strings. A typo in the class name or ID means the element will never be found.
3
Guard against null. Always check if the returned value is null before using it:
const el = document.querySelector('#myBtn'); if (el) { el.addEventListener('click', handler); }

Example 1: Script in <head>

A student places their script in the <head> and wonders why nothing works.

✕ Broken
<head> <script> const btn = document.querySelector('#go'); btn.addEventListener('click', run); // TypeError! </script> </head> <body> <button id="go">Start</button> </body>
✓ Fixed with defer
<head> <script defer src="app.js"></script> </head>

Example 2: Dynamic Content

Elements added after page load (via fetch, innerHTML, or frameworks) won't be caught by selectors that already ran.

✕ Broken: binding before element exists
// Runs on page load const card = document.querySelector('.card'); // null! card.addEventListener('click', flip); // Later, an API response adds the card: container.innerHTML = '<div class="card">...</div>';
✓ Fixed with event delegation
// Bind to a parent that already exists document.querySelector('#container') .addEventListener('click', function(e) { if (e.target.matches('.card')) { flip(e.target); } });

Example 3: querySelectorAll is Static

Unlike getElementsByClassName, the NodeList from querySelectorAll is a static snapshot. New elements added later will not appear in the list.

const items = document.querySelectorAll('.item'); console.log(items.length); // 3 // Add a new .item to the page container.insertAdjacentHTML('beforeend', '<div class="item">New</div>'); console.log(items.length); // Still 3, not 4!
querySelectorAll
Static NodeList: a frozen snapshot at call time. Does not update.
getElementsByClassName
Live HTMLCollection: automatically reflects DOM changes in real time.

Event Listener Timing Traps

Even when your selector works, the listener itself can suffer from timing problems. Two classic traps:

1. Double binding
Running your script twice (e.g., on navigation in a SPA) attaches the same handler twice. The callback fires multiple times per click.
2. Stale closures
A listener captures a variable's value at creation time. If the variable changes later, the handler still sees the old value.
// Fix double binding with { once: true } or AbortController btn.addEventListener('click', handler, { once: true }); // Fix stale closures: read current value inside the handler btn.addEventListener('click', () => { console.log(getCurrentCount()); // always fresh });

innerHTML Destroys References

Setting innerHTML on a parent replaces all child nodes. Any previously stored references or event listeners on those children become invalid.

Before innerHTML #container .btn ✓ .card ✓ → After innerHTML #container new .btn new .card listener attached no listener! Old nodes are garbage collected. New nodes have no listeners. Use event delegation or re-bind after innerHTML changes.

Common Mistakes

✕ Typo in selector
Using ".submitt-btn" instead of ".submit-btn". No error is thrown: you just get null.
✕ Missing # or .
Writing querySelector('myId') instead of querySelector('#myId'). Selectors follow CSS syntax.
✕ Using async for DOM scripts
The async attribute does not wait for the DOM. Use defer instead for DOM-dependent code.

Summary: Strategies at a Glance

Strategy Solves Best for
Script at bottom of <body> Null selectors Simple pages
defer attribute Null selectors External scripts
DOMContentLoaded Null selectors Inline scripts
Null check (if / ?.) Runtime crashes Defensive coding
Event delegation Dynamic content SPAs, AJAX
AbortController Double binding Re-renders

Question 1 of 5

A <script> tag is placed inside <head> without any attributes. It calls document.querySelector('#app'), where #app is a <div> in <body>. What is the return value?

Question 2 of 5

Which attribute should you add to a <script> tag in <head> to ensure the DOM is fully parsed before the script executes?

Question 3 of 5

You bind a click handler to .card elements at page load. Later, new .card elements are added via an API call. The new cards don't respond to clicks. What is the best fix?

Question 4 of 5

What happens to event listeners on child elements when you set the parent's innerHTML to a new string?

Question 5 of 5

What is the key difference between a static NodeList (from querySelectorAll) and a live HTMLCollection (from getElementsByClassName)?