skip to Main Content

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


  1. if you variable is a global try using this window["variableName"].innerHTML = myValue;

    let firsthtmlelement = document.getElementById("firsthtmlelement");
    let secondhtmlelement = document.getElementById("secondhtmlelement");
    const button = document.getElementById("button");
    
    const array = ['firsthtmlelement', 'secondhtmlelement'];
    
    
    button.addEventListener("click", function() {
      console.log(array[1]);
      //in this example we will just hardcode which element to change
      window[array[1]].innerHTML = "Hello World";
    });
    <div id="firsthtmlelement">div1</div>
    <div id="secondhtmlelement">div2</div>
    <button id="button">press</button>
    Login or Signup to reply.
  2. 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.

    const elementsObject = {
      "firsthtmlelement": document.querySelector("#firsthtmlelement"),
      "secondhtmlelement": document.querySelector("#secondhtmlelement")
    };
    
    elementsObject["firsthtmlelement"].innerHTML = "Hello World 1";
    
    const elementsArray = [document.querySelector("#firsthtmlelement"), document.querySelector("#secondhtmlelement")];
    
    elementsArray[1].innerHTML = "Hello World 2";
    <div id="firsthtmlelement"></div>
    <div id="secondhtmlelement"></div>
    Login or Signup to reply.
  3. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search