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

175
Views
get all button elements dragged into div element

im trying to make any button elements can be dragged into a div. in the end i want to make sure that any new button i made can be dragged into a div. i tried using querySelectorAll to grab any element, but it doesn't work like expected. right now only one button can be dragged into a div. here is the code

let button = document.querySelector('button')
let div = document.querySelector('div')

// for button
button.addEventListener('dragstart', function (ev) {
  let lol = ev.dataTransfer.setData("text", 'button');
  console.log(lol)
})


// for div
div.addEventListener('dragover', function (ev) {
    ev.preventDefault()
})
div.addEventListener('drop', function (ev) {
  ev.preventDefault()
  ev.target.appendChild(document.querySelector('button'));
})
#div1 {
    width: 350px;
    height: 70px;
    padding: 10px;
    border: 3px solid #fff555;
}
  <div id="div1"></div><br>
    <button draggable="true">button one</button>
    <button draggable="true">button two</button>

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You do need use querySelectorAll, and use forEach on the returned NodeList to attach the event handler to each button.

dataTransfer is then set with the appropriate id, which need to be added in the HTML.

This property is then read back in the drop event handler.

let buttons = document.querySelectorAll('button')
let div = document.querySelector('div')

// for button
buttons.forEach(button=>button.addEventListener('dragstart', function (ev) {
  let lol = ev.dataTransfer.setData("text", ev.target.id);
  console.log(ev.target.id);
}));


// for div
div.addEventListener('dragover', function (ev) {
    ev.preventDefault()
})
div.addEventListener('drop', function (ev) {
  ev.preventDefault()
  ev.target.appendChild(document.getElementById(ev.dataTransfer.getData("text")));
})
#div1 {
    width: 350px;
    height: 70px;
    padding: 10px;
    border: 3px solid #fff555;
}
  <div id="div1"></div><br>
    <button id='b1' draggable="true">button one</button>
    <button id='b2' draggable="true">button two</button>

about 4 years ago · Santiago Gelvez 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!