0

I added an event listener for my button element but it is not firing as expected.

The following is what I have tried so far:

var Button = document.getElementsByClassName("buttons");

var bButton = document.getElementsByClassName ("buttons2");

var cButton = document.querySelector ("#inputNew");


Button.addEventListener("click", function (random){
    alert ("clicked") });
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
  • You can't add addEventListener to `getElementsByClassName`, it can returns more than 1 element, you need to do `Array.from(Button).forEach(button => button.addEventListener(...));` – Pavlo Jun 10 '18 at 10:47
  • You should use getElementById as the function you are using could give more than one element. – Ryan_DS Jun 10 '18 at 10:47

1 Answers1

0

getElementsByClassName doesn't return a single element but returns a collection of elements as a NodeList Object which you'll need to loop through each one of them using say, forEach.

However, if your buttons have separate class names, you should just use querySelector instead like this:

var aButton = document.querySelector("buttons");

var bButton = document.querySelector("buttons2");

var cButton = document.querySelector("#inputNew");

aButton.addEventListener("click", function (random){ alert ("clicked") });
bButton.addEventListener("click", function (random){ alert ("clicked") });
cButton.addEventListener("click", function (random){ alert ("clicked") });
AndrewL64
  • 15,794
  • 8
  • 47
  • 79