Skip to content

How to display JavaScript variable value in HTML table | Code

  • by

Using getElementById and innerHTML property you can display JavaScript variable value in HTML table. Here is 2 step to do it.

Use ids to the cells you want

<td id="data1">text</td> 

<td id="data2">text</td> 

You can set their value in JavaScript like this

document.getElementById("data1").innerHTML = data1;
document.getElementById("data2").innerHTML = data2;

Example display JavaScript variable value in HTML table

Simple example code. Use the script below the element to avoid errors.

<!DOCTYPE html>
<html>

<body>

  <table>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
    <tr>
      <td>January</td>
      <td id="data1">$0</td>
    </tr>
    <tr>
      <td>February</td>
      <td id="data2">$0</td>
    </tr>
  </table>

  <script type="text/javascript">
    var data1 = "$100";
    var data2 = "$80";

    document.getElementById("data1").innerHTML = data1;
    document.getElementById("data2").innerHTML = data2;
  </script>

</body>
</html>

Output:

How to display JavaScript variable value in HTML table

Do comment if you have any doubts or suggestions on this JS variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *