javascripthtmlintersection-observer

Intersection Observer using querySelectorAll throws a TypeError


I'm getting stuck on a Intersection Observer problem. Using document.querySelectorAll('.entry') throws a TypeError: "Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'."

Changing document.querySelectorAll('.entry'); to document.querySelector('.entry'); solves the issue and it works.

What am I doing wrong?

The basic HTML structure:

<html>
<body>
  <div id="content-container">
    <div class="content">
      <div class="entry">Some content here on each entry</div>
      <div class="entry"></div>
      <div class="entry"></div>
      <div class="entry"></div>
      <div class="entry"></div>
      <div class="entry"></div>
    </div>
</div>
</body
</html>

The JavaScript:

const blog = document.querySelectorAll('.entry');
const options = {
  root: null,
  rootMargin: '0px',
};
const observer = new IntersectionObserver(function(entries, observer) {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      return;
    } 
    else {
      console.log(entry);
    }
  });
}, options);
observer.observe(blog);

Solution

  • This issue happens because IntersectionObserver.observe() can only observe one targetElement but using document.querySelectorAll() you are passing a NodeList representing a list of the document's elements that match the specified group of selectors. Thus you are having an issue with it, but document.querySelector() only gives you first matched element thus there is no issue when you use this.

    You can resolve this issue by looping through all elements in the list and observe each of them indivdually like:

    const blogs = document.querySelectorAll('.entry');
    blogs.forEach(blog => observer.observe(blog));