1

When I click start,some choices will be displayed.

I would like to select each choice by getElementById is it possible?

How can I change my work to achieve it ?

Thanks

document.getElementById("start").addEventListener('click',function(){
  html=" ";
  for (let i=1;i<=4; i++){
    html+= "<button id='choice'>"+"choice"+i+"</button><br>";
  }
  document.querySelector('.btn').innerHTML = html;
});

document.getElementById("choice").addEventListener('click',function(){
  console.log(this);
});
<div class ="btn"><button id="start">start</button></div>
Mamun
  • 58,653
  • 9
  • 33
  • 46
Heisenberg
  • 2,855
  • 1
  • 16
  • 31

1 Answers1

2

You should attach the event on elements when they are present in the DOM. Also, the attribute id must be unique in a document.

You can try the following way:

document.getElementById("start").addEventListener('click',function(){
  html=" ";
  for (let i=1;i<=4; i++){
    html+= `<button id=choice${i}>choice${i}</button><br>`;
  }
  document.querySelector('.btn').innerHTML = html;

  document.querySelectorAll("[id*=choice]").forEach(function(el){
    el.addEventListener('click',function(){
      console.log(this);
    });
  });
});
<div class ="btn"><button id="start">start</button></div>
Mamun
  • 58,653
  • 9
  • 33
  • 46