Adding every single table located in a div onto the body of the document

In my code, there is a div containing 3 tables.

var x = tempDiv.getElementsByClassName("hiscore_table");

I can confirm this because when I log it in the console, it shows like this:

https://i.sstatic.net/iYBB8.png

To organize the tables, I create a new div to append them to:

var newDiv = document.createElement('div');

for (let i = 0; i < x.length; i++) {
    newDiv.appendChild(x[i]);
}

However, when I append the new div to the body, only 2 tables are visible. After debugging, I noticed that the loop is only running 2 times even though x.length returns 3. I suspect that when I append child, it might be deleting the tables from the old div, causing this issue.

Answer №1

When you create a fresh <div> and add existing elements from the DOM to it, you are essentially eliminating those elements from the DOM to place them in the new <div> (which is not part of the DOM).

It's important to note that HTMLCollections (the result of document.getElementsByClassName) are dynamic lists. This implies that any changes made to the DOM immediately impact the collection.

Initially, with i being 0, you append the first element, thereby reducing the collection to just two elements.

Subsequently, with i set to 1, you append the second element from the remaining collection, effectively the third element overall, leaving only one element in the collection.

As the loop continues and i becomes 2, it surpasses the bounds of the now single-element collection.

This scenario is reminiscent of deleting items from an HTMLCollection.

Various methods can be employed to tackle this issue, such as iterating in reverse order. Alternatively, a functional method is my preferred choice:

Array.from(x).forEach((table) => newDiv.appendChild(table));

This technique immediately converts the HTMLCollection into an array, making it non-dynamic.

Answer №2

For the sake of inclusivity, in order to provide compatibility for older browsers without relying on polyfills or other similar solutions (e.g. sustaining resilient and easily maintainable code), you could employ a while loop:

while (x[0]) {
  newDiv.appendChild(x[0]);
}

Alternatively, a straightforward approach is to utilize querySelectorAll, which yields a static NodeList:

var x = tempDiv.querySelectorAll(".hiscore_table").

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

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

Create the artwork on cube surfaces as a complete unit, rather than focusing on the individual triangles that form the face - three.js

While trying to paint each face of a cube with a different color, I came across a helpful thread that outlines a method to achieve this: var geometry = new THREE.BoxGeometry(5, 5, 5); for (var i = 0; i < geometry.faces.length; i++) { geometry.faces ...

Challenge encountered with Promise failing to resolve despite multiple retry attempts

I've been struggling with Promises as a beginner for the past few days. I need to make an API call and check if there is a response. If not, I have to retry calling the API a configurable number of times. I attempted the following code, but I'm u ...

What is the method for toggling a checkbox on and off repeatedly?

I've been struggling with this piece of code. I've attempted using setTimeout, promises, and callback functions, but nothing seems to work as expected. document.querySelectorAll("input").forEach((el, i) => { setTimeout(() => { ...

Efficiently transferring components of a JavaScript project between files

For the first time, I am creating an npm package using ES6 and Babel. However, I am facing difficulties in connecting everything together so that it can be imported correctly by the end user. The structure of my build (output) folder is identical to src: ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

Automatically bypassing git conflicts in package.json: A step-by-step guide

We encounter frequent updates to shared npm packages in our app, resulting in multiple pull requests updating the same package version. Consequently, conflicts arise on GitHub when these pulls are merged into the master branch. Is there a way to automati ...

Checking that an object's keys are all present in an array in TypeScript should be a top priority

I am working with a const object that is used to simulate enums. My goal is to extract the keys from this object and store them in an array. I want TypeScript to generate an error if any of these keys are missing from the array. // Enum definition. export ...

Exploring Angular Firebase Database Queries

This is my TypeScript file import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; @Component({ selector: 'app-candidate- ...

Using jQuery to show/hide linked CSS3 animations upon Mouseenter/Mouseleave events

Exploring the capabilities of animate.css and jQuery within a bootstrap environment has been quite interesting for me. However, I've encountered a major issue! I am attempting to trigger animations on mouseenter / mouseleave, which led me to create a ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

Include the distribution file from the npm package in the final build

Working on my react-based project, I've integrated the node-poweredup npm package to enhance functionality. This useful library comes in both a nodejs and browser version. To include the browser version in my app, I simply link the script located at j ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...

Prevent unexpected page breaks in <tr> elements on Firefox (Could JavaScript be the solution?)

Wondering if there are any ways, possibly through JavaScript or CSS, to avoid having page breaks within <tr> elements specifically in Firefox. Given that FF does not yet fully support page-break-inside, I assume this might need to be addressed using ...

Discovering the precise location of the required() file

When using the require function in the `node` console with commands such as require('path') or require('assert'), how can I determine the absolute path of the file that was loaded? I have searched everywhere for a clear answer without ...

Origin of SVG Circle Stroke

Describing my current issue is proving to be challenging, but I'll do my best: My project involves creating an SVG circle progress bar and fortunately, I came across a great example that aligns with what I aim to achieve. I prefer not to use any thir ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

Unexpected Token E encountered in the Twitter stream.on function

I'm currently in the process of setting up a search button on my web application that will pull all Twitter tweets related to the search input using the streaming API. Below is my client-side code: <form class="navbar-form navbar-left" role="sear ...

Refreshing RadioGroup selection in React.js

Currently, I am in the process of developing a quiz application using React. In order to create multiple-choice questions, I have integrated Material-UI for radio button inputs. However, I am encountering an issue where the selected buttons are not clearin ...

What is the best way to incorporate a dropdown menu into existing code without causing any disruption?

I've come across this question multiple times before, but I still haven't found a suitable answer or solution that matches my specific situation. (If you know of one, please share the link with me!) My goal is to create a basic dropdown menu wit ...