I have the following code in JavaScript:
var counter=0;
for(..){
Element.innerHTML = '<div id="myId">....</div>';
counter++;
}
and i want to do the following, generating the ID dynamically:
for(..){
var counter=0;
...
Element.innerHTML = '<div id="myId'+counter+'">....</div>';
...
counter++;
}
I have the following code in JavaScript:
var counter=0;
for(..){
Element.innerHTML = '<div id="myId">....</div>';
counter++;
}
and i want to do the following, generating the ID dynamically:
for(..){
var counter=0;
...
Element.innerHTML = '<div id="myId'+counter+'">....</div>';
...
counter++;
}
counter
is reset to 0
at each iteration of for
loop?
– guest271314
Commented
Jul 24, 2016 at 18:02
Move
var counter = 0;
outside of the for loop, because you reset it on every loop.
var counter = 0;
for(...){
//...
Element.innerHTML = '<div id="myId'+counter+'">....</div>';
//...
counter++;
}
Don't use a separate counter if you are already using a for loop.
Don't use capitalized Element
as a variable name. It is already a DOM interface and I can't think of a reason you should be overriding that. Even if it causes no current issues in your code, it's bad practice.
var element = document.body // or grab any dom node
var someAmount = 10 // or any amount
// assuming you are looking to add additional divs with each iteration
// which is what I assume you mean by 'concatenate'
for (var i = 0; i < someAmount; i++) {
element.innerHTML += '<div id="myId'+i+'">....</div>'
}