javascript - How to concatenate Attribute value in innerhtml? - Stack Overflow

admin2025-04-20  0

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++;
}
Share Improve this question edited Jul 25, 2016 at 7:02 Oscar asked Jul 24, 2016 at 17:58 OscarOscar 71 gold badge1 silver badge3 bronze badges 3
  • 4 So what's the problem? – Quentin Commented Jul 24, 2016 at 17:59
  • 1 Appears one issue is counter is reset to 0 at each iteration of for loop? – guest271314 Commented Jul 24, 2016 at 18:02
  • sorry the counter is already outside of the loop,the code is very long, and tried to reduce. im looping through JSON objects and transforming them to HTML divs dynamically, i thought i had a mistake, but it was already right. I just forgot to make the same changes in other divs using the ID (bootstrap Collapse, popover...). And i need for my template each loop a new ID, to produce a different div – Oscar Commented Jul 25, 2016 at 7:01
Add a ment  | 

2 Answers 2

Reset to default 2

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>'
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745112860a285681.html

最新回复(0)