What is causing the issue with JavaScript textContent not correctly assigning the text in this code snippet?

I recently attempted an exercise from the MDN website that involved using JSON to extract data and display it on a webpage. The code seems to be functioning correctly, generating the desired strings. However, I encountered an issue where the generated strings were not being assigned to the textContent properties of newly created paragraphs. Interestingly, when I manually performed the assignment in the console, it worked flawlessly.

"""

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <section>

        </section>
        <script>
            const section = document.querySelector('section');


            let requestURL = "https://raw.githubusercontent.com/mdn/learning-area/master/javascript/oojs/tasks/json/sample.json";
            let request = new XMLHttpRequest();
            request.open("GET", requestURL);
            request.responseType = "json";
            request.send();


            let kittenInfo;
            let motherInfo = "The mothers are";


            request.onload = function() {
                let catString = request.response;
                extractInfo(catString);
            }

            function extractInfo(info){
                let end = ", ";;
                let total = 0;
                let male = 0;
                let names = "";

                for (let i = 0; i < info.length; i++) {
                    if (i === info.length - 2) {
                        end = " and";
                    }else if (i === info.length - 1){
                        end = ".";
                    }
                    motherInfo += " " + info[i].color + " " + info[i].breed + " " + info[i].name + end;

                    for (let j = 0; j < info[i].kittens.length; j++) {
                        end = ",";
                        if (i === info.length - 1) {
                            if (j === info[i].kittens.length - 2){
                                end = " and";
                            }else if (j === info[i].kittens.length - 1){
                                end = ".";
                            }
                        }

                        if (info[i].kittens[j].gender === "m"){
                            male += 1;
                        }

                        names += " " + info[i].kittens[j].name + end;
                        total += 1;
                    }
                }
                kittenInfo = `There are ${total} kittens, ${male} of them are male and ${total - male} of them are female. ` + 
                      `Their names are ${names}`;
            } 


            let para1 = document.createElement("p");
            let para2 = document.createElement("p");

            para1.textContent = motherInfo;
            para2.textContent = kittenInfo;

            section.appendChild(para1);
            section.appendChild(para2);

        </script>
    </body>
</html>

Answer №1

Prior to obtaining a response from the HTTP request, you are already establishing the text content.

To address this issue, consider relocating the para1.textContent = ..., etc., within your extractInfo() function.

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

Prevent Console tracing in Angular when encountering errors with $http requests

As I work on my application, I rely on a REST api to fetch my data. When I make a request like this: $http.get('api/entity/' + $scope.entityId).success(/* DO STUFF */).error(/* DO STUFF */) In the service, if the entityId is not found, I return ...

Setting the header for the $http.post function in AngularJS 1.3.5 - a step-by-step guide

After developing a REST webservice, I encountered an error in my Java code related to MIME media types. To resolve this issue, I attempted to include 'Content-Type': 'application/x-www-form-urlencoded' or 'Content-Type': &apos ...

Troubleshooting unexpected behavior with Custom Guest middleware in Nuxt Project

I have implemented the Nuxt auth module for my project. To manage the login page, I created a custom middleware called guest.js, which has the following code: export default function ({ $auth, store, redirect }) { if (!process.server) { if ($auth ...

"OBJLoader Three.js r74, bringing vibrantly colored elements to your 3

It's a straightforward process, I import my OBJ model that was exported using 3DS Max. I have the intention of coloring a specific section of the Object. During the animation loop, I implement the following: scene.traverse( function( object ) { ...

What is the best way to dynamically update the selected option in a dropdown menu within a Rails application using a variable?

Working on a project that involves a select drop-down menu containing a list of currencies. Want to enhance user experience by automatically selecting the default value in the dropdown based on the user's country (will be utilizing the geoip gem). To ...

Convert a JavaScript array of objects into an array of arrays

I'm searching for a more elegant ES6 solution to transform this array: var src = [{x:1,y:'a'},{x:2,y:'b'}]; Into this array: var desc = [[1,2],["a","b"]]; This new array should contain one array for all properties and another a ...

The image is not appearing on mobile devices, but it is displaying correctly on desktop computers

Having trouble with my landing page on compare.comxa.com. When I try to view it on my Android device, only the form shows up and the background image is nowhere to be found. Can anyone help me troubleshoot this issue? Here is the code: ...

The fetch API is failing to transmit data through a post request

I am struggling with sending data via post using the Fetch API as the server only receives an empty JSON. Can anyone offer assistance? Essentially, I am updating the data in the state and then sending it to the API. submitedData = request. submitedData ...

Activate hover effect on iOS by tapping, not clicking

For the longest time, I believed that the hover effect on iOS devices only appeared when a complete "click" or "touch" occurred. However, my perspective changed when I came across this page: On this page, the hover effect is triggered simply by tapping on ...

Ways to extract a word from the source code of a webpage

<a class="thumb" href="/pe/Productos/Marca/Nike/Nike-Air-VaporMax-2020-FK/p/bt_NE_10677654" title="Nike Air VaporMax 2020 FK"> <img data-src="//media.marathon.store/products/h75/h1b/h00/9012525662238.jpg" alt="Nike Air VaporMax 2020 FK" class="laz ...

A user-friendly JavaScript framework focused on manipulating the DOM using a module approach and aiming to mirror the ease of use found in jQuery

This is simply a training exercise. I have created a script for solving this using the resource (function(window) { function smp(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; i ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

Swap out any terms in a sentence that correspond to words found in a different array

Looking to prefix words in a string that match specific 'filter' words with a # symbol. Here's what I've tried: let wordsArray = ['she', 'smile']; let sentence = 'She has a big smile'; let sentenceArray = ...

Create a new object with the first two keys of the array of objects as keys for the new object, and the third key as an array within that

I am dealing with JSON data from a csv file and need to extract Test and Result values for each object. My goal is to create an indicator array based on the matching Test and Result in each object. [{ "Test": "GGT", "Result ...

A guide on debugging Sass using Sencha Touch on an iPhone

After making changes to the sass file in Sencha and compiling it, I cleared the iPhone simulator and cleaned the project. Despite seeing the new styles applied in the browser, they do not reflect on the iPhone simulator or the actual device. The change I ...

What is the best way to display properly formatted code to users in a React JS application?

The backend is sending code to me in plain text format. Here's an example: def countNegatives(matrix): count = 0 for row in matrix: for num in row: if num < 0: count += 1 return count It's just basic text, but I need to show this to the user ...

Reactiveness issue with Vue JS: Javascript module variables not updating

After creating a validator module inspired by vee-validate, I wanted to use it in combination with the composition api. However, I encountered an issue where the errorMessages stored in a reactive array were not updating in the Vue template despite being s ...

Dynamically loading inter-component JS/TS in an Angular application

Hey there! I have a current component structure set up like this: appComponent --infoComponent ---beforeComponent ---afterComponent Both the before and after components have navbars with unique IDs, specifically navbar_before and navbar_after. H ...

Generating real-time video from jpeg images with Gstreamer and JavaScript's setTimeout() function

In my attempt to set up a live "video" stream, I am using an HTML tag on a web page. A continuous Gstreamer pipeline updates a file titled "snapshot.jpeg" with new frames captured from a webcam through video4linux2 at a frame rate of 15 fps. The webpage ...

Bootstrap table showing message "loading in progress, please be patient"

I'm having an issue trying to load data from an API into a bootstrapTable but it seems to be stuck on "loading..". Can anyone help me figure out what's wrong with my code? Thank you in advance for your assistance! <table id="table" ...