Joe Swindell
Joe Swindell

Reputation: 671

Javascript for loop not looping with concatenated string

HTML

<div id="this1"></div>

JS

var total = 5;
for (var i=0; i<total; i++){
    var id = "this" + i.toString();
    var s= document.getElementById("this1");
    s.innerHTML += id;
    s.innerHTML += "<br/>";
}

Output

this0
this1
this2
this3
this4

What I'd like is to change the element selector to the var id.

var s= document.getElementById(id);

When I do this the loop iterates once and stops. If I change the for loops i to 1,2,3,etc and match the html div id with that IE:

html

<div id="this3"></div>

js

for (var i=3; i<total; i++){

output

this3

I get one successful output, as I should. However, starting the iterator at 0 I get 1 loop and that's it.

Is there something fundamental I'm not noticing in my half awakeness?

Upvotes: 0

Views: 38

Answers (2)

dave
dave

Reputation: 64657

If you don't have a corresponding element (<div id="this0"> if you start at i = 0), then you will get Uncaught TypeError: Cannot read property 'innerHTML' of null and the script will halt.

Upvotes: 1

nanobar
nanobar

Reputation: 66355

That is because your loop is 0 based so you need an id of this0 otherwise it will throw an exception when you try and do .innerHtml on something that is undefined.

<div id="this0"></div>
<div id="this1"></div>
<div id="this2"></div>
<div id="this3"></div>
<div id="this4"></div>

var total = 5;
for (var i=0; i<total; i++){
    var id = "this" + i;
    var s= document.getElementById(id);
    s.innerHTML += id;
    s.innerHTML += "<br/>";
}

Also you don't need toString js knows to convert it.

Fiddle: http://jsfiddle.net/75jah/

Upvotes: 1

Related Questions