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? Thanks9 Replies
add defer to your script link
that didn't work
hmm why not just
modalcontent.classList.toggle("visible");
it's hidden by default i assume??yeah it is
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 notUnknown User•2y ago
Message Not Public
Sign In & Join Server To View
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Yup, I made a mistake. Doing some React project and I just did not think, you're right, will edit