personwholikestocode
personwholikestocode

Reputation: 561

HTML Button not creating alert

I know I am probably missing something very simple, but why isn't the alert showing up when the button is clicked? Is it something to do with the function within the "addEventListener"?

Thanks!

const button = document.getElementsByTagName("button");

button.addEventListener("click", function(event){
    alert("Heyyyy!")
})
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title></title>
 </head>
 <body>
     <p>
         <button type="button">Click Me!</button>
     </p>
  <script src=Test.js></script>
 </body>
</html>

Upvotes: 0

Views: 65

Answers (4)

Ethan Eyob
Ethan Eyob

Reputation: 29

const button = document.getElementsByTagName("button");

button.addEventListener("click", function(event){
    alert("Heyyyy!")
})
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title></title>
 </head>
 <body>
     <p>
         <button type="button">Click Me!</button>
     </p>
  <script src=Test.js></script>
 </body>
</html>
Try window.addEventListener();

Upvotes: 0

Fritzdultimate
Fritzdultimate

Reputation: 450

The reason is because getElementsByTagName(tagName) returns an Array so you must loop through it to add the event listener.

But if you only needs to add to a specific button, then use id to reference the button.

E.g

To assign to every button:

const button = document.getElementsByTagName("button");

Array.from(button).forEach((el) => {
    el.addEventListener("click", function(event){
    alert("Heyyyy!")
    })
});

The need for Array.from(element) is because HTML element is an array-like not a pure array.

To assign to a specific button:

Simply:

buttonId.addEventListener('click', function(){})

Upvotes: 0

Ibrahim Rahhal
Ibrahim Rahhal

Reputation: 331

check your console you probably have "addEventListener is not a function" error and that's because

document.getElementsByTagName("tag-name")

returns an array of DOM elements since a tag name isn't unique across the DOM elements like the id. so you have two options give the button an id and use

document.getElementById("button-id")

or just get the first item in the array

const button = document.getElementsByTagName("button")[0];

button.addEventListener("click", function(event){
    alert("Heyyyy!")
})

Upvotes: 2

user13999717
user13999717

Reputation:

You can simply use only a function and the onclick property, like this:

HTML

<button id="myButton" onclick="var msg='message'; alertFunction(msg);">Click Me!</button>

JS

function alertFunction(msg) { alert(msg); }

Upvotes: 0

Related Questions