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:


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

grandparent.addEventListener(“click”, e => {

And here the html:

  body {
    margin: 0;
    min-height: 100vh;

  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);


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. 
     parent ends here
  grandparent ends here

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">

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.