Variables in JavaScript are utilized for storing data that can be required later in the script. Developers may need to display the value of a variable in the HTML body by using JavaScript to manipulate the DOM (Document Object Model). JavaScript gives some pre-built methods or attributes to perform these tasks.
This post will explain the way for displaying a value of a variable in the HTML body.
How to Display/Show a JavaScript var in the HTML Body?
To display a value of JavaScript variable in the HTML body, use the following approaches:
Method 1: Display a JavaScript var in the HTML Body Using “document.write()” Method
One of the simplest ways for displaying a JavaScript variable in the HTML body is to use the “document.write()” method. It is a pre-built method of the “Document” object for writing a string of text to the HTML document.
Syntax
Follow the given syntax for the “document.write()” method:
Example
The web page before displaying var in the HTML body looks like this:
First, create a variable “message” that holds a text string that will display on the web page:
Pass the variable to the “document.write()” method as an argument:
Now, you can see that the message has been successfully printed on the web page:
If you want to display the text or the value of a variable on the specified element or the section on the web page, follow the given section.
Method 2: Display a JavaScript var in the HTML Body Using the “innerHTML” Property
Another way for displaying the value of the JavaScript variable in the HTML body is to utilize the JavaScript “innerHTML” attribute. It is the most commonly utilized approach to set the HTML content on an element of the web page.
Syntax
Use the given syntax for using the “innerHTML” attribute:
Example
Create a paragraph element with an id attribute in an HTML file, that will hold the variable value:
In JavaScript file or the <script> tag, call the “document.getElementById()” method to get a reference of the HTML <p> tag and set the “innerHTML” attribute to the value of the variable:
Output
We have compiled all the essential information related to the displaying JavaScript variable in the HTML body.
Conclusion
For displaying a value of a variable in the HTML body, use the “document.write()” method or the JavaScript “innerHTML” property. It is the most commonly utilized approach to set the HTML content on an element of the web page. This post explained different methods for displaying a variable in the HTML body.