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.

Get Heading Text using JavaScript Current Date in mm/dd/yyyy Format JavaScript Current Date in dd/mm/yyyy Format in JavaScript JavaScript Current Date in yyyy-mm-dd Format JavaScript Get Date Difference in Hours JavaScript Get Date Difference in Minutes JavaScript Get Date Difference in Seconds Get Last Character of String with JavaScript Trigger Button Click On Page Load JavaScript Get id Of Child Element JavaScript Get Id Of Parent Element in JavaScript Get Table Row Index onclick in JavaScript Remove specific option from Select Tag with JavaScript Change Selected Option of Select Tag with JavaScript Get Length of Text In Textarea with JavaScript Change Text Color of Select Tag Option using JavaScript Change Heading Text in JavaScript Get Input Value Length in JavaScript Toggle Button Text with JavaScript Change Background Color of Dropdown with Dropdown using JavaScript Emoji Mood Slider with HTML CSS and JavaScript Hide and Show Div with Radio Button using JavaScript Count Options In Select Tag with JavaScript Get Select Tag Text OnChange with JavaScript Change Background Color OnClick using Input Field