html code
<html>
<head>
</head>
<body>
<p>Hello world</p>
<button id="yourButton">My button</button>
<script src = "script.js"></script>
</body>
</html>
javascript code
document.getElementById("yourButton").addEventListener("click", function() {
alert("Button clicked!");
});
the console with give a cannot read properties of null error
For an alert to to happen when the button is clicked
2
Answers
Your code works just fine on my machine, double check file names or if theres could be others files in your workspace that could be causing the error
My Workspace
Sometimes the mistake can be somewhere you’re not looking. Make sure that the script.js and index.html files are in the same directory and are not mixed with any other files.