Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda