Search code examples
javascriptconcatenationinnerhtml

Reference a Javascript variable name in InnerHTML by concatenating string and integer


I have the below Javascript function where I was hoping to dynamically reference a variable from an InnerHTML by concatenating a string with an integer, but this does not seem to work (a string is returned):

function TestFunction() {
    var activity_1 = "Hello World";
    var i = 1;
    var x = 'activity_' + i;
    document.getElementById("myTest").innerHTML = x;
}

Thanks in advance.


Solution

  • Please check this code and let me know is it working or not.

    function TestFunction() {
        var obj = {activity_1:"Hello World"};
        var i = 1;
        var x = "activity_" + i;
    
        document.getElementById("myTest").innerHTML = obj[x];
    }
    
    TestFunction();
    <div id="myTest"></div>