0

This isn't so much a problem, since I know the solution, as it is a desire to understand what the problem actually is. Take this minimal example:

document.getElementById("testForm").addEventListener('submit', (event) => {
  event.preventDefault();
  document.getElementById("main").innerHTML += '<p>submitted</p>';
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="css/style.css">
  <title>Title</title>
</head>

<body>
  <main id="main" class="main">
    <form id="testForm">
      <input type="submit" name="submit">
    </form>
  </main>
</body>

</html>

This is supposed to append "<p>submitted</p>" to #main on submission. On the first click, it works as expected. On the second click, the browser seems to lose my event listener and fall back to the default behavior. It reloads the page with a query.

By slightly modifying the code to add a sibling container and appending to that, we can get this to work as expected.

document.getElementById("testForm").addEventListener('submit', (event) => {
  event.preventDefault();
  document.getElementById("response").innerHTML += '<p>submitted</p>';
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="css/style.css">
  <title>Title</title>
</head>

<body>
  <main id="main" class="main">
    <form id="testForm">
      <input type="submit" name="submit">
    </form>
    <div id="response"></div>
  </main>
</body>

</html>

So I know the solution, but I don't understand the problem.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
ABP
  • 115
  • 1
  • 1
  • 8
  • 1
    You could think of `innerHTML +=` of doing: `.innerHTML = '` - it doesn't look for similarities to previously-existing markup, it unconditionally clears whatever was in the container before and parses the new HTML string into elements. (new elements) – CertainPerformance Nov 19 '21 at 03:47

1 Answers1

1

When you modify the innerHTML of an element, you are removing all event listeners on its children.

This is because the entire tag must be reparsed, losing event listeners in the process.

Spectric
  • 30,714
  • 6
  • 20
  • 43