0

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.

0

1 Answer 1

2

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];
} 
Sign up to request clarification or add additional context in comments.

7 Comments

That doesn't work for me, though it might be (I expect it is) that my Javascript function is broken. jsfiddle.net/zzrmvwa7
I guess you haven't seen my update yet. And if you look at the console you will see that your code is invalid: Uncaught SyntaxError: Unexpected token [.
The edit doesn't work for me either. jsfiddle.net/zzrmvwa7/1 I'll investigate the error, thank you.
Yeah, additionally, 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?
Inexperience. What would you recommend I use instead?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.