1
votes

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>'
1

1 Answers

1
votes

When you do document.getElementById("container").innerHTML += "{your element}", you're effectively wiping out the existing inner elements and recreating them with one extra element. This means your previous event listeners won't be there. One way you can work around this is creating all your buttons first, then add your event listeners later. Or you could use appendChild to avoid recreating all the elements. Or better yet, use a framework like angular, react, or vue.js which will deal with this stuff for you so you don't go through the hassle of interacting with the DOM directly.