Quick Learn how to Display JavaScript Variable in HTML

How to Display JavaScript Variable in HTML?

There are many ways to display a JavaScript variable in HTML document. But the method that I use mostly will describe now.

Step 1 – Create HTML5 document

First and the most important step is to create a HTML5 document in your code editor. I use Visual Studio Code, but you can choose your own which you like to use. Below is the screenshot of the document which I created below.

display javascript variable in html

Step 2 – Create a div with ID

Now we successfully created a blank HTML5 document with basic things. Now let’s create a div with some specific Id. Here I have created a div with id of “myDiv”. And below is the screenshot of my code.

display javascript variable in html

Step 3 – Declare JavaScript variable and display in HTML

Now lets write some JavaScript code to declare our variable and display that into our HTML.

Create script tag at the end of the body, but wrapped into body tag. And add the following code in your document script tag.

<script>

let myVar = 'Some Variable';

let myDiv = document.getElementById('myDiv');

myDiv.innerHTML = myVar;

</script>

Below is the screenshot of the final code and I shall describe every line below.

display javascript variable in html

On line #11 and #15 are the script start and end tags. Which are necessary when you want to write JavaScript code into your document.

On Line #12 we have declared a variable with myVar name and assigned ‘some variable value’ to it.

Second last on line #13 we have got the div by it’s Id and saved into myDiv variable.

Lastly on line #14 we have displayed our variable by using innerHTML DOM property.

Now when you open your webpage in web browser. You will see your JavaScript variable is displayed in HTML document. Below is the screenshot where our variable value is shown.

display javascript variable in html

Congratulations! You have learned display javascript variable in html.