Skip to content

How to display JavaScript variable value in HTML page | Code

  • by

You can use the document.write if just want to display JavaScript variable value in the HTML page. But if you want to show variables to particular elements use innerHTML with getElementById.

document.write(variable)

Or

document.getElementById("myText").innerHTML = variable;

Example display JavaScript variable value in HTML page

Simple example code showing variable value into a <p> tag.

<!DOCTYPE html>
<html>
<head>
  <script>
    function myFunction() {
      var v = "Hello world";
      document.getElementById("myText").innerHTML = v;
    }
  </script>
</head>

<body onload="myFunction()">

  <p id="myText"></p>

</body>
</html>

Output:

How to display JavaScript variable value in HTML page

Use document.write()

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    var number = 123;
  </script>
</head>

<body>
  
  <script type="text/javascript">
    document.write(number)
  </script>
  
</body>
</html>

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading