Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
Why can't I modify a <form>'s parent in onsubmit events?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!