-1

I am trying to output "click" to console whenever someone clicks the button on my webpage. It's a very simple webpage, it contains only a button with the ID "buttonn". This is my code. I am trying to use a lambda to define a console.log function. I am very much a beginner, please keep this in mind when explaining. This is the first im testing out of DOM manipulation. When I try to check the console output on Google Chrome, i receive this error message: JavascriptCp.js:3 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at JavascriptCp.js:3:9

Is the code set up correctly? I am pretty sure it works, i have turned off every extension on chrome, but something tells me there may be some other problems with Chrome. I just want to rule out error from coding first. Thanks!

const button1 = document.getElementById("buttonn");

button1.addEventListener("click", () => {
    console.log("Click!")});
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="JavascriptCp.js"></script> 
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button type="button" id="buttonn"> Button!</button>
    
</body>
</html>
ayoubzann
  • 1
  • 2
  • 1
    Duplicate: [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) (your `button1` is null because the script runs before the button exists) –  Aug 21 '22 at 13:37

1 Answers1

-1

Ref. ChrisG response: The script tag came in before the buttons existence. Issue resolved

ayoubzann
  • 1
  • 2