So if I have this code:
const firsthtmlelement = document.getElementById("firsthtmlelement");
const secondhtmlelement = document.getElementById("secondhtmlelement");
const array = ['firsthtmlelement', 'secondhtmlelement']
array[1].innerHTML = "Hello World";
How can I make the secondhtmlelement’s innerHTML show up as "Hello World"?
I tried something similar to the code above, when I press something then it is supposed to change the innerHTML of a different element depending on which entry from an array I wanted.
3
Answers
if you variable is a global try using this
window["variableName"].innerHTML = myValue;
When you call arry[1] you are getting a string, and not the variable.
There are many ways to accomplish dynamic variables.
Below I have two solutions:
The first solution creates an object where the key is the name and the value is the querySelector for that element.
The second is using an array like your example.
Try to add actual elements in your
array
instead of just string names: