Skip to content

Intersection Observer Invalid Root

Quick summary

You passed a null or detached element as the observer root — intersections are never reported.

Why this happens

  • Root element was removed from the DOM before the observer was created

  • Passed a string selector instead of an Element as root

  • Root is null because querySelector found nothing

Minimal example

✗ Broken code
const root = document.querySelector('#nonexistent'); // null
const obs = new IntersectionObserver(entries => console.log(entries), { root });
obs.observe(document.querySelector('#target'));
✓ Fixed code
const root = document.querySelector('#scroll-container');
if (root) {
  const obs = new IntersectionObserver(entries => console.log(entries), { root });
  obs.observe(document.querySelector('#target'));
}

querySelector returns null for a missing selector, and using null as root can silently fail. Checking that root exists before creating the observer avoids the issue.

How to diagnose

  • Check that the root argument is a valid Element attached to the DOM

  • Verify the observer callback fires by logging entries

  • Pass null explicitly to use the viewport as root if that is intended

How to fix

  • Ensure the root element exists and is in the DOM before creating the observer

  • Pass null (not undefined) to use the browser viewport as root

  • Recreate the observer if the root element is re-attached later

How to prevent

  • Validate the root element with instanceof Element before use

  • Create observers after the DOM is ready and the root exists

Related Resources

Related Glossary

Related Lessons

  • DOM

    Learn about Intersection Observer.

← Back to language