添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Javascript – Uncaught TypeError: Failed to execute ‘observe’ on ‘IntersectionObserver’: parameter 1 is not of type ‘Element’

intersection-observer javascript

I'm watching a video on Intersection Observer and I've copied his script word for word and I'm somehow getting this error. Someone had the same error but solved their problem by changing querySelectorAll to querySelector. Even when I copied their code and changed it to querySelector it still didn't work on my end. The code below is mine. I'm using vs code live server.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel='stylesheet' href='style.css'>
    <script src='script.js'></script>
</head>
    <section class = 'section1'></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
</body>
</html>
const sectionOne = document.querySelector('.section1');
const options = {};
const observer = new IntersectionObserver(function
(entries, observer){
    entries.forEach(entry => {
        console.log(entry);
}, options);
observer.observe(sectionOne);
body{
    padding: 0;
    margin: 0;
section{
    height: 100vh;
    width:100%;
section:nth-child(odd){
    background: lightcoral

The element returns as null because the script runs before the HTML is parsed. I used defer in my script tag to avoid this problem.

<script src='script.js' defer></script>