Simple version: I have a list of arrays that reference page elements, like so:
var listOfArrays = ["header", "middle", "footer"];
and arrays like so for each:
var header = ["red", "blue", "green"];
var middle = ["carrot", "cucumber", "asparagus"];
var footer = ["earth", "air", "water"];
I'd like to be able to replace the HTML of the page elements dynamically by running through an array, like so:
for(i=0; i<listOfArrays.length; i++) {
document.getElementById(listOfArrays[i]).innerHTML({listOfArrays[i]}[cycleNumber]);
}
The output I'd like would be the three elements changed to read "red", "carrot", and "earth", respectively (at least for the first cycle, which is all I'm concerned about). How should I code this?
Here is a jsfiddle with a model of what I'm trying to do.
1 Answer 1
One solution is to create an additionally array containing the other arrays:
var IDs = ["header", "middle", "footer"];
var parts = [
["red", "blue", "green"],
["carrot", "cucumber", "asparagus"],
["earth", "air", "water"]
];
for (var i=0; i < IDs.length; i++) {
document.getElementById(IDs[i]).innerHTML = parts[i][cycleNumber];
}
Now, the disadvantage is that it is not very maintainable. If you add a new element to IDs, you have to rearrange parts accordingly.
A slightly better solution is to use an object as a lookup map:
var IDs = ["header", "middle", "footer"];
var parts = {
header: ["red", "blue", "green"],
middle: ["carrot", "cucumber", "asparagus"],
footer: ["earth", "air", "water"]
};
for (var i=0; i < IDs.length; i++) {
var ID = IDs[i];
document.getElementById(ID).innerHTML = parts[ID][cycleNumber];
}
7 Comments
Uncaught SyntaxError: Unexpected token [.innerHTML is a string, not a function. You cannot call it, you have to assign to it. What made you think it is a function?