Why is my JavaScript addEventListener not working on a button?

1 week ago 4
ARTICLE AD BOX

I'm learning JavaScript, and I'm trying to run a function when a button is clicked.
But for some reason, the function never runs, and nothing appears in the console.

Here is my code:

<!DOCTYPE html> <html> <body> <button id="myBtn">Click Me</button> <script> document.getElementById("myBtn").addEventListener("click", function() { console.log("Button clicked!"); }); </script> </body> </html>

Issue:

When I click the button, nothing happens—no output in the console.

I inspected the page and found no errors in the JavaScript console.

What I Tried:

Changing the button ID

Using onclick instead of addEventListener

Moving the script tag above the button (still didn't work)

Adding defer to the script tag

Question:

Why is my event listener not firing, and how can I fix it?

Read Entire Article