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

177
Vistas
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 Respuestas
Responde la pregunta

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