I've encountered a DOM exception that has me stuck. My issue involves div elements and a button - when the user clicks the button, a random div is selected and another div with a background-color class is appended to it. Essentially, clicking the button fills a random div container with a randomly colored div. The goal is for users to be able to drag this newly created and colored div to an empty one. However, this is where things get tricky. Below is my HTML markup:
<div class="row">
<div class="empty border"></div>
<div class="empty border"></div>
<div class="empty border"></div>
<div class="empty border"></div>
<div class="empty border"></div>
<div class="empty border"></div>
</div>
After the button click (which appends a new div), the structure changes to:
<div class="row">
<div class="empty border"></div>
<div class="empty border">
<div class="filled" draggable="true" id="test" style="background-color: rgb(242, 202, 185);"></div>
</div>
<div class="empty border"></div>
<div class="empty border"></div>
<div class="empty border"></div>
<div class="empty border"></div>
</div>
The problem arises when attempting to drop the "filled" div into a dropzone (an empty div), resulting in an uncaught exception. Here's my JS code snippet:
const prepareForDrag = () => {
let divElements = Array.from(document.getElementsByTagName('div'));
let emptyCubes = divElements.filter(cube => cube.classList.contains('empty'));
let filledCubes = divElements.filter(cube => cube.classList.contains('filled'));
emptyCubes.forEach(function (cube) {
cube.addEventListener('dragover', dragOver);
cube.addEventListener('drop', drop);
})
filledCubes.forEach(function (cube) {
cube.addEventListener('dragstart', dragStart);
})
function dragStart (e) {
emptyCubes.forEach(cube => cube.classList.add('dropzone-border'));
e.dataTransfer.setData('text/plain', e.target.getAttribute('id'));
}
function dragOver (e) {
e.preventDefault();
}
function drop (e) {
let coloredCube = e.dataTransfer.getData('text/plain');
e.target.appendChild(document.getElementById(coloredCube));
emptyCubes.forEach(cube => cube.classList.remove('dropzone-border'));
}
}
When releasing the mouse button, both the parent div and the "filled" one seem to be appended which I'm struggling to resolve. Any help or constructive feedback would be greatly appreciated :)