In this tutorial we will see how to Display JavaScript Variable In HTML. The innerHTML property and document.write() can be used to display the JS variable inside the HTML page or document.
Table of Contents
Using document.write()
document.write() is used to write HTML expression or JavaScript code to the HTML document. We can also use document.write() to display JavaScript Variable in HTML.
Code
JavaScript Code and HTML Code is given below, In this code we have used document.write() inside the paragraph tag to display the value of our JavaScript variable.
<script>
var name = "JavaScript";
</script>
<p>I Love <script type="text/javascript">document.write(name);</script></p>
Using innerHTML property
The innerHTML property sets or returns the content of HTML tags. It can also be used to display the value of JavaScript variable in HTML.
HTML Code
HTML Code is given below, In this code we have one paragraph element with id = 'main'.
<p id="main"></p>
JavaScript Code
Take a look at the JavaScript code, in this example we have a variable named 'number'.
First document.getElementById() method is used to target the paragraph element, then .innerHTML method is used to display the JavaScript variable inside the paragraph tag.
<script>
var number = "10";
document.getElementById("main").innerHTML = number;
</script>
Demo
Video Tutorial
Watch video tutorial on how to Display JavaScript Variable In HTML.