1

I have this code , where the 'innerHTML' lines is removing the onClick function from button "one" and "two" . If i disable that line, the function works for all three buttons. That 'innerHTML' in this case is doing nothing but adding empty string. I need to add something later here. But for now it's just didn't work even when it's empty string.

<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body class="body">
    <div id="buttoncontainer"></div>
    <script>
        function test() {
            alert("click");
        }
        values = ["one", "two", "three"];
        const buttoncontainer = document.getElementById("buttoncontainer");
        for (const val of values) {
            var button = document.createElement("button");
            button.id = "button_" + val;
            button.classList.add("id_button");
            button.addEventListener("click", test);
            button.textContent = val;
            buttoncontainer.innerHTML += ""; // <--- COMMENT THIS LINE TO FIX -----
            buttoncontainer.appendChild(button);
        }
    </script>
</body>

</html>
andio
  • 1,574
  • 9
  • 26
  • 45

1 Answers1

0

When you replace the innerHTML of buttoncontainer, you are deleting and recreating all the objects inside it, which loses the click event listener you've assigned.

You have a few options:

  1. You can either wait until you've completed the updates to the innerHTML of buttoncontainer before you assign the click event listener
  2. You can modify the innerHTML of a different div which does not contain your buttons
  3. Or you may be able to append other html elements to your button container instead of using innerHTML to replace the entire contents.

I would say go with option 2 or 3, but you haven't given any idea of what you plan to do to the innerHTML of the button container, so it's hard to know what would work best.

pgallo
  • 48
  • 8