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

140
Vistas
appendChild onclick will only add div once

I'm doing a timetable and to do list website. So, I basically add divs for each timetable block. I've used this tutorial on yt (https://youtu.be/MkESyVB4oUw) for the timetable blocks. (At 24:03) So in HTML there's inputs in a form and he uses the constant "form" for it and uses an addEventListener submit. I've used this and all my timetable blocks work fine. I can add multiple blocks and everything works well.

After that I made a to do / goals section and I decided to take the "form" into my own hands. So I did:

// I tried const and var and the same thing happened
const todoAdd = document.querySelector("#new-todo");   // This is the button
const weekDiv = document.querySelector("#week-divs");

const todoDiv = document.createElement('div');
todoDiv.classList.add("todo-div");

This is what I did for the time blocks and it worked, and then I added:

todoAdd.onclick = function(){
  weekDiv.appendChild(todoDiv);
}

When I do it like this, the div is added once and that's it. If I keep clicking the div just gets replaced again and again.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I figured this out mid-writing it. Because when the addEventListener starts for the form, that's when I did all the appending. So the simple solution to this was simply adding the createElement inside the function.

  todoAdd.onclick = function(){
    const todoDiv = document.createElement('div');
    todoDiv.classList.add("todo-div");
    
    weekDiv.appendChild(todoDiv);
  }

I probably could've realised this sooner if I wasn't so confused about it actually working just once. I thought there was something missing instead of a simple mistake. I'm guessing it only appends once because it is only read once, while in an onclick function or addEventListener it always loops and re-reads it right? That's my thoughts. Hope this helps someone maybe.

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