Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 286
Sackadelic Avatar asked Jun 16 '26 03:06

Sackadelic


1 Answers

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));
like image 107
palaѕн Avatar answered Jun 18 '26 16:06

palaѕн



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!