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
9 Replies
Mannix
Mannix2y ago
add defer to your script link
Lord Of Insanity
Lord Of InsanityOP2y ago
that didn't work
Mannix
Mannix2y ago
hmm why not just modalcontent.classList.toggle("visible"); it's hidden by default i assume??
Lord Of Insanity
Lord Of InsanityOP2y ago
yeah it is
13eck
13eck2y 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 User2y ago
Message Not Public
Sign In & Join Server To View
Trifke00
Trifke002y ago
<button onClick='openModal'>Click</button>

<script>
//First way
const openModal = () => {
alert('click!')
logic...
}

//second way
function openModal(){
logic...
}
</script>
<button onClick='openModal'>Click</button>

<script>
//First way
const openModal = () => {
alert('click!')
logic...
}

//second way
function openModal(){
logic...
}
</script>
~You called function when button was rendered, don't type '()', just ~you can make reference to that Fn with event. Better way of doing it would be with .addEventListener
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Trifke00
Trifke002y ago
Yup, I made a mistake. Doing some React project and I just did not think, you're right, will edit
Want results from more Discord servers?
Add your server