Here are some code snippets and comments that should help you. Where you have id='i'
, it looks like you want this: '<img id="'+i+'"'
. You concatenate in JavaScript using the +
sign, so close your string with a quote, then concatenate, then open the string up again. It's easier to learn by breaking this up into steps. Here's the string without the value: '<img id=""'
Then, you'll need to go in between the double quotes and close and open the string with single quotes, and concatenate i
, so this: '+i+'
. Altogether, you get '<img id="'+i+'"'
var num = 2;
// addEventListener is better practice than onload
window.addEventListener('load', function() {
// get the element reference before the loop (no need to repeat this)
var testElem = document.getElementById('test');
for(i = 0; i < num; i++) {
// create an img element, this is better practice than using innerHTML
var img = document.createElement('img');
img.src = "//placehold.it/100x100";
img.id = 'image'+i;
testElem.appendChild(img);
}
});
<div id="test"></div>
You could also use innerHTML
by concatenating the new image as in the following example, but this has drawbacks. Read more about createElement vs innerHTML here.
var num = 2;
window.addEventListener('load', function() {
var testElem = document.getElementById('test');
for(i = 0; i < num; i++) {
testElem.innerHTML+= '<img id="image'+i+'"src="//placehold.it/100x100">';
}
});
<div id="test"></div>