0

I'm getting the error "Uncaught TypeError: Cannot set property 'onclick' of null" in the console. Below is the code.

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

The modal window functions just fine on my site. Not sure why I'm seeing this error in the console. Does anyone know how to correct this or if it's something that I really need to worry about? Thx

jcfromkc
  • 65
  • 5
  • Which particular line is causing the error? It may be that your element isn't named exactly what you are querying for. Also, make sure that the JavaScript is executing AFTER the DOM has finished being parsed. Do this by placing your `script` just before the closing `body` tag. Also don't use [`document.getElementsByClassName("close")[0]`](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). Use `document.querySelector(".close")` instead. – Scott Marcus Dec 07 '20 at 18:45
  • The line causing the issue is. `btn.onclick = function() { modal.style.display = "block"; }` – jcfromkc Dec 07 '20 at 19:05
  • 1
    could you post the HTML, at least the `myBtn` part please. – Manu Sampablo Dec 07 '20 at 19:07

0 Answers0