JavaScript

Display a JavaScript variable in an HTML page

In this tutorial, we are going to see how to display a JavaScript variable in an HTML page by using two method, the first one is using the document.write() method and the second is using the innerHTML property.
 

Example 1: Using document.write()
<html>
   <head>
      <script type="text/javascript">
         var sum = 1 + 2;
      </script>
   </head>
   <body>
      <h1>
         The sum is
         <script type="text/javascript">
            document.write(sum)
         </script>
      </h1>
   </body>
</html>

Output:

The sum is 3
 

Example 2: Using the innerHTML property
<html>
   <body>
      <h1>
         The sum is <span id="sum"></span>
      </h1>
   </body>
   <script type="text/javascript">
      var sum = 1 + 2;
      document.getElementById("sum").innerHTML=sum;
   </script>
</html>

Output:

The sum is 3
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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