Jump to content
Stef's Super Nerd Community
hiimrann

innerHTML and while loop (JS ch7, l3)

Recommended Posts

I expect the browser to print the values from 10 to 1 in an empty p tag using JavaScript, but it's printing 1 to 10.

Why does it print above the old line, and not below it?

<!-- Button for printing "i" -->
<input type="button" value="print i">

<!-- Empty p tag where the values of "i" will be printed -->
<p></p>

<script>
  // Function for printing "i"
  function print() {
    var i = 10;
    while(i > 0) {

      // Grabs the empty p tag
      var p = document.getElementsByTagName("p")[0];

      // Prints the values of "i" on the p tag
      p.innerHTML = "i: " + i + "<br>" + p.innerHTML;
      i = i -1;
    }
  }

  // Calls the function for printing "i"
  document.getElementsByTagName("input")[0].onclick=function() {
    print();
  }
</script>

 

test-standalone.html

Edited by hiimrann

Share this post


Link to post
Share on other sites

It's alright, I worked it out with a little help.

If anyone's wondering, the answer is in the following line of code:

p.innerHTML = "i: " + i + "<br>" + p.innerHTML;

I'll explain it with two iterations, in four steps each.

Hopefully I got it right, and explained it in non-nerd well lol.

 

[Iteration 1]
Step 1. When i = 10, the browser prints the following in the <p> tag:

i: 10 <br>

Step 2. p.innerHTML (right of the = operator) is empty for now, hence, nothing happens on the screen in this step.

Step 3. The printed line (i: 10 <br>) is assigned to p.innerHTML (left of the = operator).

Step 4. i is decremented by -1, and now i = 9.


[Iteration 2]
Step 1. i = 9, and the browser FIRST prints the following in the <p> tag:

i: 9 <br>

Step 2. p.innerHTML (right of the = operator), which is now i: 10 <br>, is added after i: 9 <br>, and the browser NOW displays i: 9 <br>i:10 <br>.

Step 3. The printed line (i: 9 <br>i:10 <br>) is assigned to p.innerHTML (left of the = operator).

Step 3. i is decremented by -1, and now i = 8.
 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...