JavaScript is used to enhance the user experience on the website by adding user interactivity. You surely need to print a value of a variable in JavaScript to an HTML web page. This post will teach you 3 ways to print a variable in JavaScript.
How to Print a Variable on HTML Page with innerHTML
You can use innerHTML in JavaScript to print a variable on the screen. You first need to refer to a DOM node where you want to display the value. The following example prints the variable in a heading element with innerHTML
.
1 2 3 4 5 |
<h1 id="header"></h1> |
1 2 3 4 5 6 |
const header = document.querySelector("#header"); header.innerHTML = "latestjavascript.com"; |
Please read more about the innerHTML on mozzila documentation.
Using innerText
to Print a Variable in JavaScript
You can also use innerText
in JavaScript to print a variable value on an HTML web page. The innerText
is similar to innerHTML
in use but it actually just changes the text inside the tag. The following code snippet use innterText
to change the text content of the header.
1 2 3 4 5 6 |
const header = document.querySelector("#header"); header.innerText = "latestjavascript.com"; |
Here is more details about the innerText on mozzila documentation.
How to Print a Variable Using console.log
The console.log
function is very helpful in debugging. You can use it to print a variable value on the console. To see the output of console.log
you need to go to developer options > console in the browser. Here is a simple example of printing the variable with console.log
1 2 3 4 5 6 |
var website = "latestjavascript.com"; console.log(website); |
Conclusion
There are a couple of ways to print the value of a variable in JavaScript. You can use console.log
if you are just debugging the code. The innerHTML
and innerText
is used to print the variable in an HTML web page.