0

I want to use for loop to create multiple variables. I want to create

var node0 = document.getElementById("refresh_table_0");
node0.innerHTML="";
var node1 = document.getElementById("refresh_table_1");
node1.innerHTML="";
var node2 = document.getElementById("refresh_table_2");
node2.innerHTML="";

this is my imagination code:

for(i=0;i<3;i++){
var node+i = document.getElementById("refresh_table_i");
node+i.innerHTML="";
}
1
  • Any time you think you want a bunch of numbered variables, you're almost certainly doing it wrong. You should use an array. And if you think you need dynamically-named variables, you should use an object. Commented Jan 18, 2014 at 6:43

2 Answers 2

1

First, this is javascript.
Second, the imagined code has errors, should be ("refresh_table_" + i).

Try using js arrays instead.

var node = new Array();
for(i=0;i<3;i++){
    node[i] = document.getElementById("refresh_table_" + i);
    node[i].innerHTML="";
}
Sign up to request clarification or add additional context in comments.

Comments

0

To just initialize all the items, you can simply do this as there's no need to retain each separate DOM object:

var node;
for (var i = 0; i < 3; i++) {
    node = document.getElementById("refresh_table_" + i);
    node.innerHTML = "";
}

Or, even just this:

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

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.