Search code examples
javascripthtmlarraysgetelementbyid

Pass variable into document.getElementById() - Javascript


I am running a function that populates several paragraph tags on a webpage with the days of the week. The function takes an array of days which is populated based on the current day (i.e. if today is Thursday, get the next 7 days in order).

My problem is that for some reason, I am unable to populate these tags. I have checked to make sure that the array is getting populated and the list is being iterated through. While both of these are true, none of the Inner HTML of the tags are being changed.

HTML:

<p class="mb-1" id="forecastDay1" runat="server">Day</p>
<p class="mb-1" id="forecastDay2" runat="server">Day</p>

JavaScript Function:

function populatePage(arry) {
    var i;

    for (i = 0; i < arry.length - 1; i++) {
        var id = "forecastDay" + i.toString();
        document.getElementById(id).innerHTML = arry[i].toString();
    }
}

I have also tried it this way:

document.getElementById("forecastDay" + i.toString()).innerHTML = arry[i].toString();

Solution

  • You do not need toString in JavaScript.

    Also, arrays start at 0, while your elements start at 1. You have to compensate that difference.

    function populatePage(arry) {
      var i;
    
      for (i = 0; i < arry.length; i++) {
        var id = "forecastDay" + (i + 1);
        document.getElementById(id).innerHTML = arry[i];
      }
    }
    
    // Test it
    populatePage(["Day 1", "Day 2"]);
    <p class="mb-1" id="forecastDay1" runat="server">Day</p>
    <p class="mb-1" id="forecastDay2" runat="server">Day</p>