Search code examples
javascripttype-conversioninnerhtml

How to convert text into variable name to print its value using innerHTML?


I have a function that writes a text into html document. This text is equal to the values of two variables, and the result is equal to the name of a third variable. How can I convert this final text into a variable name to make the function print it's value?

<script>
function start()
{
var name1 = "name";
var name2 = 3;
var name3 = "Text that I want to write";

document.getElementById('here').innerHTML = name1 + name2;


}
</script>

<div id="here"></div>

<button onclick="start()">
Start
</button>

UPD: There was a tupo var name1 = "test", it should be var test1 = "name"


Solution

  • Try using an object!

    <script>
    function start() {
      var names = {
        name1: "name",
        name2: "3",
        name3: "Text that I want to write"
      }
    
      document.getElementById('here').innerHTML = names[names.name1 + names.name2];
    }
    </script>
    
    <div id="here"></div>
    <button onclick="start()">start</button>