I'm trying to run two buttons to show two pop-ups. I don't understand why CODE A below doesn't work but CODE B works. When I press the "press1" button on CODE A, nothing happens. Must I output all my HTML together at once? I'm trying to run a for-loop so how could I output both working buttons?
CODE A
document.getElementById("buttondiv").innerHTML += '<tr><td><button class="press1">Press Me</button></td></tr>';
//Find all buttons on the page with the name transferToken
var button1 = document.querySelector('button.press1');
button1.addEventListener('click', function () {
alert("Hello John");
});
document.getElementById("buttondiv").innerHTML += '<tr><td><button class="press2">Press Me</button></td></tr>';
var button2 = document.querySelector('button.press2');
button2.addEventListener('click', function () {
alert("Hello Jane");
});
CODE B
document.getElementById("buttondiv").innerHTML += '<tr><td><button class="press1">Press Me</button></td></tr>';
document.getElementById("buttondiv").innerHTML += '<tr><td><button class="press2">Press Me</button></td></tr>';
var button1 = document.querySelector('button.press1');
button1.addEventListener('click', function () {
alert("Hello John");
});
var button2 = document.querySelector('button.press2');
button2.addEventListener('click', function () {
alert("Hello Jane");
});