The .append() function has a tendency to only add a portion of the elements

var mainUrl = "http://127.0.0.1:8000/";
var ajaxHot = document.getElementById("hotajax");
var ajaxPopular = document.getElementById("popularajax");
var ajaxToday = document.getElementById("todayajax");
var ajaxCurrent = document.getElementById("partial-index");
var ajaxIndex = document.getElementById("ajax-index");

function retrieveAjaxContent(ajaxButton, endpoint) {
    ajaxButton.addEventListener("click", function () {
        var request = new XMLHttpRequest();
        var parser = new DOMParser();
        request.open("GET", mainUrl + endpoint);
        request.onload = function () {
            var responseString = request.responseText;
            var responseDocument = parser.parseFromString(responseString, "text/html");
            var contentToAppend = responseDocument.getElementById("content-body").children[1];
            ajaxCurrent.children[0].children[0].innerHTML = responseDocument.getElementById("content-body").children[0].innerHTML;
            while (ajaxIndex.hasChildNodes()) {
                ajaxIndex.removeChild(ajaxIndex.lastChild)
            }
            console.log(contentToAppend.childElementCount);
            for(i=0; i<contentToAppend.childElementCount; i++) {
                ajaxIndex.append(contentToAppend.children[i])
            }
        };
        request.send();
    });
}

retrieveAjaxContent(ajaxHot, "titles/hot/");
retrieveAjaxContent(ajaxPopular, "titles/popular/");
retrieveAjaxContent(ajaxToday, "titles/today/");

I am attempting to fetch elements from a URL and insert them into the ajaxIndex element, but I am encountering unexpected behavior.

---> The while statement is removing all child elements.

---> The console log outputs the total number of new titles which should be either 25 (for hot and today) or 4 (for popular).

---> However, the next statement only appends half of the expected titles, such as 13 out of 25 or 2 out of 4.

If I slightly modify the code like this:

        for(i=0; i<contentToAppend.childElementCount; i++) {
            console.log(contentToAppend.children[i])
        }

It correctly logs all 25 (or 4 for popular) titles from the new page. But when I try to append them:

        for(i=0; i<contentToAppend.childElementCount; i++) {
            console.log(contentToAppend.children[i]);
            ajaxIndex.append(contentToAppend.children[i]);
        }

The result is that it both appends and logs only 13 (or 2 for popular) new elements.

I have even manually set the loop count to i<25, yet it still only appends 13 elements and adds "undefined" text to the HTML.

My question is twofold: why is this happening, and how can I go about fixing it?

Answer №1

One important thing to remember is that a DOM node cannot exist in two DOM trees simultaneously. So, when you use the .append() method within a loop, it not only appends the node to the specified parent but also removes it from its current parent. As a result, each time you increment the variable i, you end up skipping over the next node.

Furthermore, keep in mind that the .append() method is still experimental and may not be supported by all browsers. To ensure better compatibility, consider using the .appendChild() method instead.

If you need to correct this issue, one simple solution would be to modify your for loop as follows:

while( newtitles.firstChild ) {
    console.log( newtitles.firstChild );
    ajaxindex.appendChild( newtitles.firstChild );
}

Additionally, it's worth mentioning that there was a missing var or let declaration in your original for loop. This problem doesn't arise in the revised while loop implementation.

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

What happens in mongoose if one of several consecutive queries fails?

Currently, as I work on my API, I am utilizing two Models: SongModel and UserModel. Whenever a new song is saved, I also execute a query to link the song._id to the user who created it. Unfortunately, a mistake in my code caused the second query to throw a ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

Advanced Text Formatting Tool with Table, Picture, and Document Upload Capabilities

Searching for an open source Rich Text Editor that can handle tables, images, and file uploads while keeping a slim design. Popular options like tinymce or ckeditor are too bulky and lack image and file upload capabilities. ...

A guide on passing an array parameter using JavaScript

I need to transfer an array of ids from one page to another. I have created the $ids variable in PHP, and I am using it with jQuery like this: var ids = <?php echo json_encode($ids); ?>; jQuery(ids).each(function() { filters.push('ids[]=&a ...

Using Xero webhooks in combination with Node-RED: a match made in heaven or a disaster

Lately, I've been caught up in the world of cryptography and it's been keeping me up at night. The challenge started when I decided to implement a node red solution for receiving webhooks from Xero and integrating them into a custom app. Dealing ...

Issues with Vuex store causing incorrect value retrieval

In troubleshooting this issue, I am encountering a problem. My request to the back end is to retrieve data for display on the front end. The data fetched from the backend consists of recipes stored in an array. Utilizing v-for, I iterate through the array ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...

What is the best way to make asynchronous calls synchronous in JavaScript?

I am working with JavaScript on the client-side and Node.js on the server side. I attempted to implement remote validation for input fields where the result should be a boolean value based on a server call. Here is my code: jQuery.validator.addMethod("re ...

Creating a dynamic tbody element on button click with the help of javascript or jquery

I am working with the following code: $(document).ready(function() { //Optimizing by selecting tbody first using jquery children var tbody = $('#myTable').children('tbody'); //If no tbody found, select the table itself ...

Striving to incorporate a Facebook like button onto a Sencha toolbar

The issue I'm facing is that the like button isn't visible on my webpage. Here's a snippet of the code: HTML file : . . . <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElem ...

Automatically sync textbox width with gridview dimensions

My goal is to dynamically resize a number of textboxes so that they match the width of my gridview's table headers. The gridview will always have the same number of columns, but their widths may vary. However, as shown in the image below, the width va ...

Custom tooltip in Chart JS is not displaying as expected

I have created a line graph and I am looking to customize its tooltip. When hovering over the graph, I want it to display the following information: Question: This is question 1 Your answers: 3 Average answers: 7 Your average: 5 Average: 7 The data in th ...

When the submit button is clicked, only the last form within the function will be submitted

I currently have a submit button that is meant for 3 different forms. When submitting, I use the following approach: restaurantCreateForm = function(){ document.getElementById("restaurant-features" ).submit(); document.getElementById("information_ ...

Utilizing Jquery Ajax to send a post request containing input values through Tampermonkey

I encountered an issue with my code - even though the logs in console show that it is working, I am unable to send the values to my server using AJAX post. jQ(document).on("keyup", "form input", function () { var value = jQ(this).val(); ...

Despite having configured WCF CORS, I am still encountering the issue of not receiving the 'Access-Control-Allow-Origin' header

Whenever I try to access a WCF service across different domains, I encounter this error: The XMLHttpRequest cannot load . The response to the preflight request fails the access control check due to the absence of the 'Access-Control-Allow-Origi ...

Generate a mongoose output by iterating through a loop within Koa.js

My current setup involves using Koa.js in combination with Mongoose.js. Within my MongoDB database, there exists a collection called css which has the following schema: _id css_name css_value In my code, I have an array that contains a large number of el ...

Creating HTML dynamically using AJAX techniques

Looking for suggestions on a topic I am working on. Specifically, I am interested in finding the best method or pattern for dynamically constructing HTML. This task is quite common for me: Sending data to a server via POST --> receiving a JSON list of ...

Vue.js: Optimize Webpack bundle by excluding core-js

Below is the content of my vue.config.js file: module.exports = { configureWebpack: { externals: { "vue": "Vue", "core-js": "core-js", }, }, }; By using this configuration, I have successfully excluded the vue.js (Vue) library and ...

What is the best way to format dates in jQuery AJAX requests?

Utilizing jquery to interact with a REST API in (ASP.net Web API). I've constructed a basic object and then utilized jquery to 'PUT' it on the server: var myObject = { name: 'just a name', createDate: new Date() } $.ajax({ ...

The function toJson() does not exist for the specified stdClass object

After following a tutorial on implementing websockets in Laravel to create a live commenting system, I encountered an error that I cannot figure out. Even though I followed the code exactly as demonstrated in the video, this error persists. Does anyone hav ...