HTML display variable text | Example code

  • by

Use document.getElementById or document.write() to display variable text in HTML. If you wan to show variable value into a particular element use getElementById.

HTML display variable text

Simple example code show variable value into a h1 tag.

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

<body onload="myFunction()">

  <h1 id="myText" ></h1>

</body>

</html

Output:

HTML display variable text

Or use it without funciton

<body>

  <h1 id="myText" ></h1>

  <script>
    
    var number = "Hello 123";
    document.getElementById("myText").innerHTML = number;
    
  </script>

</body>

Use document.write()

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

<body>
    <h1>
      the value for number is:
      <script type="text/javascript">
        document.write(number)
      </script>
    </h1>
</body>
</html>

Do comment if you have any doubts or suggestions on this HTML 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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.