0

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?

0

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I'm not used to writing JS, that fixed it perfectly, I can close this in a couple minutes when it lets me.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.