Get the corresponding button value in a loop
P粉056618053
P粉056618053 2024-03-30 12:57:23
0
2
471

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粉056618053
P粉056618053

reply all(2)
P粉254077747

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>

P粉575055974

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 `);
}

const btn = document.querySelectorAll(".allbuttons")
for (var i = 0; i 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template