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

138
Views
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 answers
Answer question

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 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!