Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda