Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Lee Cockcroft
Lee Cockcroft
5,147 Points

For loops

Hi All,

Could someone explain something to me please.

For loops with the statement "document.write(i);"

Lists what I want it to list.

However if I "document.getElementByid" (and obviously select a id)

eg

for(var i=0;i<9;i++) {

document.write(i);

}

this works fine, however the below just prints 8?!

for(var i=0;i<9;i++) { document.getElementByid("output").innerHTML=i;

}

Any ideas?

Thanks

2 Answers

andren
andren
28,558 Points

The second example just prints 8 because you are setting the innerHTML value equal to i in each loop, when you set a value equal to something it replaces whatever was there before. It doesn't add to it. So whatever i is at the end of the loop is what innerHTML will be equal to at the end of the loop, if you use += (which adds a value rather than sets it) instead like this:

for(var i=0;i<9;i++) { 
  document.getElementById("output").innerHTML += i;
}

Then you will end up with the same effect.