For this kind of thing, there are arrays , which are an indexed collection of data.
Instead of doing variavel1
, variavel2
, you use a variable only, and an index of which of the data stored within it refers ( variavel[1]
).
To initialize a array already with data:
var lista = [
1,
2,
3
];
var nomes = [
'Zé',
'Maria',
'Chico'
];
As in your case you will use a loop , you can start with an empty array, and append new data to an array without erasing or overwriting the JS has method push
:
lista = [];
lista.push(30);
lista.push(12);
lista.push(53);
// lista passou a ser [30, 12, 53]
See a very simple example of creating 10 independent information using array :
var lista = []; // aqui criamos um array vazio de nome "lista"
var i;
for(i = 0; i < 10; i++ ) {
// troque o i * i pelo que quiser armazenar
// por exemplo, push( document.createElement( ... ) );
lista.push( i * i );
}
document.body.innerHTML += "O valor de lista[5] é " + lista[5];
In your case, just do this in the line of push
lista.push( document.createElement("DIV") );
And to use any item, simply enter the index between brackets:
lista[5].innerText = 'Cinco';