title: How to use intersection observer to add class to element until the next element is reached, then add class to that one etc
body: <p>I want to use an <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API" rel="nofollow noreferrer">intersection observer</a> to see when a certain part of my page has been reached.
  My page is divided by a few sections with ids, for example #section1, #section2, #section3 etc.</p>
  <p>At the top of my page is a sticky menu with buttons to navigate to each section. I want to highlight the button that a user is currently viewing.</p>
  <p>So when scrolling to section 1, highlight section1 button but when scrolling further down, keep it highlighted until section2 has been reached (with a little offset, maybe 300px so a user scrolls a bit past the divider until it highlights), then highlight that button.</p>
  <p>How can this be done?</p>
  <p>I made this:</p>
  <pre><code>function selectElementById(idname) {
    return document.querySelector(`#${idname}`);
  }
  
  const sections = [
    selectElementById('top'),
    selectElementById('bestellen'),
    selectElementById('informatie'),
    selectElementById('inspiratie'),
    selectElementById('reviews'),
  ];
  
  const navItems = {
    top: selectElementById('topbtn'),
    bestellen: selectElementById('bestellenbtn'),
    informatie: selectElementById('informatiebtn'),
    inspiratie: selectElementById('inspiratiebtn'),
    reviews: selectElementById('reviewsbtn'),
  };
  
  const observerOptions = {
    root: null,
    rootMargin: '-175px 0px 0px 0px',
    threshold: 0.7,
  };
  
  function observerCallback(entries, observer) {
    entries.forEach((entry) =&gt; {
      if (entry.isIntersecting) {
        // get the nav item corresponding to the id of the section
        // that is currently in view
        const navItem = navItems[entry.target.id];
        // add 'active' class on the navItem
        navItem.classList.add('activeprodmenu');
        // remove 'active' class from any navItem that is not
        // same as 'navItem' defined above
        Object.values(navItems).forEach((item) =&gt; {
          if (item != navItem) {
            item.classList.remove('activeprodmenu');
          }
        });
      }
    });
  }
  
  const observer = new IntersectionObserver(observerCallback, observerOptions);
  
  sections.forEach((sec) =&gt; observer.observe(sec));
  </code></pre>
  <p>But I get this error: <code>Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.</code></p>