Understanding the reverse order of numbers displayed with while loop and innerHTML

function doItAgain() {

            var loopCount = 5;

            while(loopCount > 0) {

                    var target = document.getElementById("target");
                    target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML;
                    console.log("LoopCount is now: " + loopCount);
                    loopCount = loopCount -1;
                }

Here we have a function that executes a loop five times when triggered by a button click event handler.

The question at hand is why the numbers are displayed on the webpage from 1 to 5 when pressed, but in the console they count down from 5 to 1. Changing the position of the sentence within target.innerHTML can reverse the order, but the reason for this behavior remains unclear.

Answer №1

Think about the functionality of this particular line:

target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML;

Assume that after the first loop, target.innerHTML contains:

LoopCount: 5<br>

Then during the loopCount = 4 loop, you are executing:

target.innerHTML = "LoopCount: " + loopCount + "<br>" + target.innerHTML;

once again, resulting in

target.innerHTML = "LoopCount: " + loopCount + "<br>" + "LoopCount: 5<br>";
// -----------------------------------------------------^^^^^^^^^^^^^^^^^^

and hence you receive

LoopCount: 4<br>LoopCount: 5

and so forth.

If you switch the positions of innerHTML on that line, you will alter the order:

target.innerHTML = target.innerHTML + "<br>LoopCount: " + loopCount;

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

Divide Angular ngFor into separate divs

Here is an example of my current array: [a, b, c, d, e, f, g, h, i] I am aiming to iterate through it using ngFor and split it into groups of 3 elements. The desired output should look like this: <div class="wrapper"> <div class="main"> ...

What is the correct way to remove listeners in componentWillUnmount using React, and why is binding necessary in the constructor?

I'm feeling a bit perplexed, can someone explain the distinction between these two snippets of code: constructor(props) { super(props); this.state = { openPane: false } this.togglePaneHelper = this.togglePaneHelper.bind(this); ...

Removing all items with a specific ID and its related items in Javascript: How to achieve this recursively?

I am currently facing some challenges in figuring out the most effective approach for this scenario. For example, consider the data structure below: const arr = [{ parentId: 1, children: [ { childId: 11 }, { childId: 21 }, { childId: 31 }, ...

Having difficulties with Vue components displaying in Laravel's blade.php file

Let me share my current setup with you: This is the main "Welcome.blade.php" file where I have included relevant information as the file is quite lengthy: <div id='app'> <router-view></router-view> </div> <script src ...

Validation of textfields using React.js

Currently, I am working on implementing a validation feature in ReactJS. Specifically, I have a field named "name" and my requirement is that every time a name is entered, it must be equal to or greater than 2 characters. The validation works fine when t ...

Pressing the enter key does not submit the Vue.js form

When attempting to submit the form by pressing "enter" on the keyboard, it only works when I click the "submit" button. I made sure to add @submit to the form event to ensure it triggers, but upon checking a log, I found that it only triggers when clicking ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

I am working with AngularJS and I am having trouble redirecting my pages from the main screen. I am implementing the ng-route module. Can you take a look at my code and provide feedback?

I have encountered an issue with my index.html code. I am unable to load login.html when clicking on the login button. <!doctype html> <html ng-app="instagram"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compitable" co ...

What is the best way to dynamically change the color of my component depending on the prop passed to it?

I am facing an issue with the color of my component changing based on the value of the prop 'level'. Despite using states to set the backgroundColor, all components end up having the same color due to the state being altered for every comment. I ...

Javascript does not execute properly in Google Apps Script

Encountering issues while attempting to execute the code provided in Google app script. // 1.foldername = Folder name | 3.templateId = ID of the template to use // 2.SheetId = ID of spreadsheet to use. | 4.rootFolder = ID of the root fold ...

You can only use the angularjs http function once

After browsing through similar forum posts, I was unable to find a solution to my issue. It could be due to my limited experience with JavaScript and Angular. Here's the problem: Desired Outcome: When I click a button, I want the data from the server ...

Building better interfaces with Next.js, Styleguidist, and Fela for React applications

Has anyone successfully set up next.js with Fela and Styleguidist? I'm having trouble linking the Next.js webpack configuration to Styleguidist as mentioned in this article: I've been using this example app: https://github.com/zeit/next.js/tree ...

Alert: Mouse Exiting Window - Moodle Prompt

I have created an online exam using the Moodle platform, coded in PHP. I am now looking for a way to prevent test-takers from navigating away from the test by implementing a mouseover pop-up. Below is the code I have for triggering an alert pop-up when th ...

What is the best way to guide users to different pages on the website without disrupting the socket connection?

I am looking to create a user-friendly web application utilizing socket.io and express. This website will consist of two main pages: the "Rooms" page and the individual "Room" page. The "Rooms" page allows users to input their name, create a new room, or j ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Extension for Chrome browser

I am new to creating Chrome extensions and I am attempting to build one that will display the IDs of all elements with a specific class name on a website in the popup window. I would like to know if there is a better way to tackle this issue. Thank you for ...

Update the browser URL dynamically without redirecting the page, by utilizing JavaScript after an AJAX call receives a

I am currently endeavoring to find a solution to replace the URL on my page without triggering a reload. My approach involves utilizing an infinite scroll JavaScript plugin. Upon receiving a response from an AJAX call, I intend to update the URL with the n ...

The issue arises when the cache code in jQuery Ajax interferes with the callback function, causing it to

I encountered an issue with my code related to cache. The problem arises when there is an ajax call with a callback in the success function. var localCache = { /** * timeout for cache in millis * @type {number} */ timeout: 30000, ...

Understanding the res.render method in JavaScript can be a bit tricky at first

In my spare time, I have been immersing myself in coding lessons and have encountered some puzzling aspects of the code: Firstly, there is a confusion surrounding the action attribute in HTML Secondly, this particular piece of code is causing me some b ...

Tips for converting text from an HTML input field to a JSON file

After designing a form with four text fields and a submit button, my goal is to save the data into a JSON file upon submission. Additionally, I am looking for a way to display all of the JSON data on my webpage. ...