Having trouble with missing elements while looping through Javascript Node.AppendChild()?

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.

Answer №1

To make the child nodes iterable, you must first convert them into an array.

function moveNodesToDestination(dbField) {
    sourceBox = document.getElementById(`${dbField}_selected`).childNodes; //List of nodes to be moved
    destinationBox = document.getElementById(`${dbField}_available`); //destination for the nodes

    [...sourceBox].forEach(child => destinationBox.appendChild(child));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to eliminate the border of an image attribute pulled from an input field?

Seeking assistance with a persistent issue I'm facing. I have an input for an image and a script to display the selected image. However, when the input is empty, a frustrating black border appears around the image attribute. How can I remove this bord ...

Upgrade jQuery visibility and opacity animations to pure JavaScript for a more lightweight solution

Currently I am in the process of removing jQuery from an older website. However, I have encountered a problem with an animation that is currently being used. I have managed to replicate the opacity fade effect, but I am struggling to smoothly transition t ...

Designing a custom style for a select box using CSS and HTML

Recently, someone assisted me in removing the outline of my select box in my debut bootstrap-django project. Now, I am seeking your guidance on altering the border color property of the options box itself from blue to yellow. Strangely, when the select box ...

Error: The value of data.isbn is not defined

After encountering the error message below: TypeError: data.isbn is undefined I modified the code to include the data.isbn == null condition as shown below: $.ajax({ type: "POST", url: "getInventory.php", datatype: "json", data: ({skuSta ...

Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no. <input type="button" name="yes" onclick="button()"> <input type="button" name="no"> In order to enhance user experience, I am looking to i ...

A declaration of "import '***.css';" was located within an ECMAScript module file in the monaco-editor npm library

It's perplexing to me why the developers of monaco-editor included these statements, as they are actually causing errors in my browser such as: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME typ ...

Updating a Zendesk ticket with multiple comments

I've been attempting to update a ticket on Zendesk using their API and adding multiple comments. However, it seems that I might be utilizing the incorrect format as the comments are not showing up on my Zendesk dashboard... The JSON format I'm c ...

I am looking to create a counter in NextJS that will store its value in a database for persistent storage. How can

In my NextJS and ReactJS project, I am creating a like-counter feature that will keep track of the number of likes a user can give. The maximum limit for likes is set to 100. The count is stored in a FaunaDB. While I have successfully displayed the curren ...

Exploring the power of pagination using Django and ExtJS

Extjs offers a gridpanel with pagination functionality, but I believe that the pagination only works once all the data has been received from the server (please correct me if I am mistaken). In my situation, the total amount of data from the server is 20MB ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

Apply styles specifically to elements that contain a child element

I have a scenario where there are multiple <p> elements with the same class names, but only one of them has a child element. My objective is to highlight only the <p> that contains a child, however, my current code ends up highlighting all of t ...

Utilizing jQuery's .ready() method within the body section of a document to modify the onload event following the printing of the body

Recently, I took over a tabbed page that uses multiple queries to determine which tabs should be displayed. My goal is to add some PHP logic that will automatically set focus on a specific tab when the page finishes loading. I'm wondering if it&apos ...

Implementing html5mode in Express.js and Angular.js for cleaner URLs

I've been working on resolving the issue of avoiding # in my Angular app with an ExpressJS server-side setup. I found a solution to enable html5mode and it worked well. However, whenever there is another 'get' request to fetch data from a di ...

Establishing the Backbone router configuration

Having trouble identifying the issue with my Backbone router. Is there an error within this code block? The index route is functioning correctly, but the classes route doesn't seem to be triggered (for example, when I try navigating to a URL like loca ...

What strategies can I use to enhance the quality of a document I'm about to create? (Using Firebase and React)

I am looking to include a Username field in a firebase user's document when creating it. This is my approach : Fill out the form with email, password, and username fields - SUCCESS. Use the email and password to sign up with firebase (createUserWith ...

Is there a way to automatically activate the "Add" button when I hit the enter key in the text box?

Being someone who relies on to-do lists, I implemented a system where you can input tasks into a textbox and click the add button to see them listed below. However, I found it cumbersome to keep clicking the add button every time I wanted to quickly add mu ...

Making a Call with Twilio using Node.js

Currently, I am working on a click-to-call website that is powered by Twilio. The process involves configuring a TwiML app and writing Twilio JavaScript SDK client-side to send requests to Twilio. Once this is done, Twilio will initiate a POST request to t ...

use dotenv in your Build Folder

Is it possible to have my .env file in my React JS project move to the build folder when I run NPM build command? If so, how can this be achieved? If not, what would be the alternative solution? I attempted using "build": "cp .env.template ...

Creating a JavaScript and C# popup for deleting records in asp.net

I'm struggling a bit with understanding how server-side deletion works. I know how to use MessageBox, but it's not the best approach. I've been advised to use a popup on the server side. What I'm trying to achieve is that when you clic ...