skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search