Home  >  Q&A  >  body text

Get the corresponding button value in a loop

querySelectorAll doesn't seem to get the list of buttons once I add a set of dynamic buttons from the array. Here is my code: Where did I go wrong?

const btns = document.getElementById("container");
const textBtn = ["btn 1", "btn 2", "btn 3", "btn 4", "btn 5", "btn 6"]
for (i = 0; i < textBtn.length; i++) {
  btns.insertAdjacentHTML('beforeend', `<button  class="allbuttons" value=${textBtn[i]}>${textBtn[i]}</button>`);
}

const btn = document.querySelectorAll(".allbuttons")
for (var i = 0; i < btn.length; i++) {
  btn[i].addEventListener('click', function(event) {
    //console.log( btn[i]);
    console.log(event.target.value);
    alert(event.target.value)
  });
}
<div id="container"></div>

P粉056618053P粉056618053202 days ago440

reply all(2)I'll reply

  • P粉254077747

    P粉2540777472024-03-31 09:53:04

    Your problem may come from: <button class="allbuttons" value=${textBtn[i]}>${textBtn[i]}</button>

    Your value is not between quotes<button class="allbuttons" value="${textBtn[i]}">${textBtn[i]}</button>

    reply
    0
  • P粉575055974

    P粉5750559742024-03-31 00:47:14

    Help? Is this what you need?

    const btns = document.getElementById("container");
    const textBtn = ["btn 1", "btn 2", "btn 3", "btn 4", "btn 5", "btn 6"]
    for (i = 0; i < textBtn.length; i++) {
      btns.insertAdjacentHTML('beforeend', ``);
    }
    
    const btn = document.querySelectorAll(".allbuttons")
    for (var i = 0; i < btn.length; i++) {
      btn[i].addEventListener('click', function(event) {
        console.log(event.target.value);
        alert(event.target.value)
      });
    }

    reply
    0
  • Cancelreply