Stephen McKenna
Stephen McKenna

Reputation: 1

JavaScript document.querySelector() isn't recognizing elements from HTML

I am trying to add scroll-triggered animations to my online portfolio website, and between my experience listings I have simple divs just as separators:

<div class='divider'></div>

that I am trying to add entrance animations to.

My JS is as follows:

//Scroll triggered animations
    const obs = new IntersectionObserver(entries => {
        entries.foreach(entry => {
            console.log(entry);
            if(entry.isIntersecting) {
                entry.target.classList.add('divider-animation');
            }
        });
    });

    console.log(document.querySelectorAll(".divider"));

    const dividerList = document.querySelectorAll(".divider");

    dividerList.foreach(divider => {
        obs.observe(divider);
    })

The console.log() statement with the querySelectorAll is returning an empty NodeList even though my dividers are placed in the HTML directly, so I'm unsure why my querySelector isn't recognizing them.

I'm suspicious that the JS is executing before the the elements are fully loaded, but I haven't had success with several different wait methods for that.

Upvotes: 0

Views: 387

Answers (1)

MOR&#200;
MOR&#200;

Reputation: 2570

Even if you are placing the script at the bottom make sure it gets executed after the DOM is loaded.

Also, it's forEach, not foreach.

window.addEventListener("DOMContentLoaded", function() {
  const obs = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      console.log(entry);
      if (entry.isIntersecting) {
        entry.target.classList.add('divider-animation');
      }
    });
  });

  console.log(document.querySelectorAll(".divider"));

  const dividerList = document.querySelectorAll(".divider");

  dividerList.forEach(divider => {
    obs.observe(divider);
  })
}, false);
<div class='divider'></div>

Upvotes: 6

Related Questions