QuerySelector is not selcting my query on Web Browser

Hello there, I am trying to replicate the starter of an exercise I found online on eventListeners i wrote the corresponding small html with the included, and in a linked .js, the 5 line code supposed to console.log the click events on one of the area mentionned in the html, in this case “grandparent”.

My issue is that when checking in the browser’s console i get this error.
“eventlist.js:5 Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)
at eventlist.js:5:13”
As far as I know my “class” is defined, the “const” too, but for some reason the browser doesn’t seem to get the value of the “const”. Any ideas ?

Best regards.

Code below:

eventlist.js

const grandparent = document.querySelector(".grandparent")
const parent = document.querySelector(".parent")
const child = document.querySelector(".child")

grandparent.addEventListener(“click”, e => {
console.log(e)
})

And here the html:

Document
<style>
  body {
    margin: 0;
    min-height: 100vh;
  }

  body,
  div {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .grandparent {
    width: 200px;
    height: 200px;
    background-color: red;
  }

  .parent {
    width: 130px;
    height: 130px;
    background-color: blue;
  }

  .child {
    width: 60px;
    height: 90px;
    background-color: rgb(9, 255, 0);
  }

</style>

It may be the case that you don’t have an html element that has a class of grandparent.

Maybe something like this …

<div class="grandparent"> grandparent starts here
  <div class="parent"> parent starts here
     <div class="child"> I'm the child element. 
     </div>
     parent ends here
  </div>
  grandparent ends here
</div>

Hi, dont know why but my html is incomplete on my first post, the script is included in head and the end of my html is:

<div class="grandparent">
  <div class="parent">
    <div class="child">
    </div>
  </div>
</div>

If your script tag is at the beginning of your html, you may need the defer attribute in there (so the JavaScript runs after the rest of the page is loaded).

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

Well, thanks a lot, didnt know about those 5 letters but defer was definitely the attribute I needed !!

Works just fine now.