Home > front end >  How to fix Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
How to fix Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

Time:05-15

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 >
        <li >Calculator App</li>
        <li >Vending Machine App</li>
        <li >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

CodePudding user response:

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

CodePudding user response:

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.

  • Related