'How to fix Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') [duplicate]

I am adding an event listener to an HTML element, so that when you click on it the drop-down displays, but for some reason, I get the Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') error, I am not sure how to fix that?

HTML el code

 <li class = "nav-item projects">
  <a class ="nav-link" href="#">Projects
   <img class = "down-arrow" src="images/icons/down_arrow_icon.png" alt="Down_arrow_icon">
  </a>
</li>

 <div class ="project-list">
      <ul class="flex-column">
        <li class="project-item ">Calculator App</li>
        <li class="project-item">Vending Machine App</li>
        <li class="project-item">Landing Page</li>
      </ul>
    </div>

I have separated the project-list from the main list as it is a separate element on its own. The nav-item projects is part of a nav,but i am only using that part of the nav for the javascript eventListener

JS event listener

let projects = document.querySelector(".projects");
let projectList = document.querySelector(".project-list")

projects.addEventListener('click', function handleMouseOver(){
    if(projects){
        projectList.style.display = "block"
    }
})

I have the



Solution 1:[1]

It look like you put your script tag before your html element try to put it after it

Solution 2:[2]

The problem is that the code is not reading the .project item (using the querySelector) at all. Check that the element is loaded in the DOM when this script is being executed (for example , listen to the event on document load) and then it should work, make sure your js code snippet is at the end of the body tag and not in the head or any place before the end of your body tag.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohamad Al Zohbie
Solution 2