I encountered an issue with a basic function designed to relocate items from one div to another using a drag and drop widget. It seems that when multiple items are being moved, the appendchild function is modifying the list directly and causing elements to be lost.
function resetm2mAlerts(dbField) {
selectBox = document.getElementById(`${dbField}_selected`).childNodes; //List of nodes to remove
availBox = document.getElementById(`${dbField}_available`); //destination of nodes
console.log(selectBox); //validating contents before loop
for(index of selectBox){
availBox.appendChild(index); //appending items to destination
}
}
Relevant HTML:
<div class="form-group">
<label for="id_default_operating_schedule">Day Of Week</label>
<div id="default_operating_schedule" class="col-md-12 nopadding twocolumndroppable">
<div id="default_operating_schedule_selected" class="col-md-6 droppable available ui-droppable">
<div id="default_operating_schedule_code_1" class="col_md_5 draggable bg-primary ui-draggable ui-draggable-handle" data-id="1">Sunday</div>
<div id="default_operating_schedule_code_4" class="col_md_5 draggable bg-primary ui-draggable ui-draggable-handle" data-id="4">Wednesday</div>
</div>
<div id="default_operating_schedule_available" class="col-md-6 droppable ui-droppable">
<div id="default_operating_schedule_code_2" class="col_md_5 draggable bg-primary ui-draggable ui-draggable-handle" data-id="2">Monday</div>
<div id="default_operating_schedule_code_3" class="col_md_5 draggable bg-primary ui-draggable ui-draggable-handle" data-id="3">Tuesday</div>
<div id="default_operating_schedule_code_5" class="col_md_5 draggable bg-primary ui-draggable ui-draggable-handle" data-id="5">Thursday</div>
<div id="default_operating_schedule_code_6" class="col_md_5 draggable bg-primary ui-draggable ui-draggable-handle" data-id="6">Friday</div>
<div id="default_operating_schedule_code_7" class="col_md_5 draggable bg-primary ui-draggable ui-draggable-handle" data-id="7">Saturday</div>
</div>
</div>
</div>
The selectBox contains only two simple examples: [<div element 1>, <div element 4>] After the first iteration of the for loop, <div element 1> gets transferred to availBox but the loop stops unexpectedly, leaving <div element 4> in the selectBox.
I tried using an indexed for loop which resulted in either out-of-bounds errors or the same issue of items remaining untransferred.
A reverse iteration of an indexed for loop solved the problem. However, my main concern is why does the append method dynamically alter the list and lead to this unexpected behavior.