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

197
Views
drag drop doesn't work for dynamically inserted element

I have a div which is a list of sections that are draggable.

I then have a drag and drop script which looks like this:

const tasks = document.querySelectorAll('.task');

tasks.forEach(task => {

  task.addEventListener('dragstart', dragStart, false);
  task.addEventListener('dragenter', dragEnter, false);
  task.addEventListener('dragleave', dragLeave, false);
  task.addEventListener('dragover', dragOver, false);
  task.addEventListener('drop', dragDrop, false);
  task.addEventListener('dragend', dragEnd, false);

});



function dragStart(e) {
  //do something
};

function dragEnter(e) {
  //do something
}

function dragLeave(e) {
  //do somehting
}

function dragOver(e) {

  //do something
}

function dragDrop(e) {
  //do something 
}

function dragEnd(e) {

  //do something
}
<div id="list">
  <section id="1" class="task" draggable="true">
    <p> Something here </p>
  </section>

  <section id="2" class="task" draggable="true">
    <p> Something here </p>
  </section>

  ...

</div>

Everything works perfectly (every section can be drag & drop).

Yet if instead of having a static HTML I do: document.getElementById('list').insertHTML(//my draggable sections) then my js script doesn't seems to work anymore. I can't drag & drop my sections.

I don't understand why, it seems like inserting the sections dynamically change something but I don't understand what... Is there a way to fix this problem ?

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

0

by element.insertHTML() do you element.insertAdjacentHTML()?
Anyways, I would guess that there's an issue with code execution order, it's probably running

const tasks = document.querySelectorAll('.task');

before you change html inside .list element. This means that const tasks ends up being empty array(it's actually empty NodeList but doesn't metter here)

Also if you don't have any specific reason to use insertAdjacentHTML, I would recomend you to use appendChild instead.

UPD

Also, every time you add new items to your list you would have to add eventListeners to each node you added.

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!