Keep getting error "Uncaught TypeError: Cannot read properties of null (reading 'classList')"

I'm making a js-actuated modal but I keep getting the error "Uncaught TypeError: Cannot read properties of null (reading 'classList')". This is my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> <title>Custom Modal</title> </head> <body> <button onclick="openModal()">Open Modal</button> <p class="modal-content hidden">This is a modal</p> <script> const modalcontent = document.querySelector(".modal-content"); function openModal() { modalcontent.classList.replace("hidden", "visible"); } </script> </body> </html> How can I fix this? Thanks
6 Replies
Mannix
Mannix16mo ago
add defer to your script link
Lord Of Insanity
Lord Of Insanity16mo ago
that didn't work
Mannix
Mannix16mo ago
hmm why not just modalcontent.classList.toggle("visible"); it's hidden by default i assume??
Lord Of Insanity
Lord Of Insanity16mo ago
yeah it is
13eck
13eck16mo ago
Get rid of the onclick attribute in the HTML and use an event listener with JS instead. Also, I would suggest using the correct element for modals: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog Add to why you’re getting the error, try declaring the target within the function and see what that does. I’m not sure if HTML attributes have access to the global variables or not
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View