0

When I click on input button, I have nothing in Console, however I expect "Hello".

This is my code:

window.onload = function() {
  const btn = document.getElementsByClassName('btn-next');
  btn.onclick = function() {
    btn.click();
    console.log("Hello");
  }
};
<input type="button" class="btn-next" value=">" />

What am I doing wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nastya
  • 3
  • 1

1 Answers1

0

You need to do document.getElementsByClassName('btn-next')[0]; as getElementsByClassName will gives the array of elements matching that class name and since you have only one element with that class use [0] to get the reference of that element.

window.onload = function() {
  const btn = document.getElementsByClassName('btn-next')[0];
  btn.onclick = function() {
    btn.click();
    console.log("Hello");
  }
};
<input type="button" class="btn-next" value=">" />

You can also use querySelector for the same purpose:

window.onload = function() {
  const btn = document.querySelector('.btn-next');
  btn.onclick = function() {
    btn.click();
    console.log("Hello");
  }
};
<input type="button" class="btn-next" value=">" />
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62