Display JavaScript Variable In HTML

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.

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.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript