Search code examples
javascriptarraysinnerhtml

How can I select the innerhtml of a variable name in an array?


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.


Solution

  • Try to add actual elements in your array instead of just string names:

    let firsthtmlelement = document.getElementById("firsthtmlelement");
    let secondhtmlelement = document.getElementById("secondhtmlelement");
    
    const button = document.getElementById("button");
    
    const array = [firsthtmlelement, secondhtmlelement];
    
    
    button.addEventListener("click", function() {
      array[1].innerHTML = "Hello World";
    });
    <div id="firsthtmlelement">div1</div>
    <div id="secondhtmlelement">div2</div>
    <button id="button">press</button>