I have looked at other questions and other sites online and have not been able to find a way to get addEventListener to work.
I have a function called which adds buttons and adds event listeners for each button
function displayData(){
for(var key in localStorage){
addButton(key);
}
}
function addButton(name){
var button = '<button id='+ name +'>'+name+'</button>';
document.getElementById("container").innerHTML += button;
// Line to add event listener
}
I have tested this many times and addButton always adds every button, but only one of the buttons works (the last one added). name is always different for each button. I have tried the following methods in Line to add event listener but none have worked
document.getElementById(name).addEventListener("click", foo);
//jQuery is included
$("#"+name).click(function(){
foo();
});
and changing
'<button id='+ name +'>'+name+'</button>'
to
'<button onclick="foo();" id='+ name +'>'+name+'</button>'