2

I have been facing an error in following code star marked option but it was executed the last run of my project but actually today it shows "Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'." on the browser.

const counters = document.querySelectorAll(".counter");
  function playCounter() {
    counters.forEach((counter) => {
      counter.innerText = 0;

      let point = +counter.dataset.count;

      let step = point / 100;

      let startCount = function () {
        let displayCount = +counter.innerText;

        if (displayCount < point) {
          counter.innerText = Math.ceil(displayCount + step);
          setTimeout(startCount, 500);
        } else {
          counter.innerText = point;
        }
      };
      startCount();
    });
  }

  let counterSection = document.querySelector(".counter_wrapper");

  let scope = {
    borderMargin: "0px 0px -200px 0px",
  };
  const sectionObserver = new IntersectionObserver(function (entry) {
    if (entry[0].isIntersecting) {
      playCounter();
    }
  }, scope);
  **sectionObserver.observe(counterSection);**
makt
  • 89
  • 2
  • 15

1 Answers1

1

In fact, because document.querySelector will return null if the element does not exist, and when element is passed to sectionObserver.observe(), if element is null, it will be thrown The above exception occurs Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element', so please ensure that the element selected by document.querySelector must exist.

Maybe you can look at this link. Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30286514) – Steak Overflow Nov 08 '21 at 23:52