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>
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>
Help? Is this what you need?