How to display JavaScript values in HTML
When you are doing front-end development, you often need to display values that are in JavaScript variables on the page using HTML.
This is useful when you are trying to debug your code or when you want to update the UI of your application.
In this post, we'll learn all the different ways you can display values in JavaScript using HTML.
Using the alert() function
The easiest way to display a value in JavaScript is to use the alert()
function. This functions entire purpose is to display a message to the user.
You can then fill in this function with the value you want to display.
JAVASCRIPTalert("Hello World!");
This is the full example:
HTML<!DOCTYPE html>
<html>
<head>
<title>JavaScript Alert</title>
</head>
<body>
<script>
alert("Hello World!");
</script>
</body>
</html>
Using document.write()
You can use document.write()
to display a value in JavaScript by writing HTML directly onto the page.
It will replace the entire contents of the page with the value you want to display.
JAVASCRIPTdocument.write("Hello World!");
If you run that, the entire page will just consist of Hello World!
.
That means you can use it to display variables by passing it in:
JAVASCRIPTconst a = "Hello World!";
document.write(a);
Using innerHTML
Probably the best and most useful way to display a value is by taking advantage of the innerHTML
property.
This property will take whatever element you call it on and replace its entire contents with the value you want to display.
JAVASCRIPTconst a = "Hello World!";
document.getElementById("demo").innerHTML = a;
Now if you have HTML like this:
HTML<!DOCTYPE html>
<html>
<head>
<title>JavaScript Alert</title>
</head>
<body>
<div id="demo"></div>
</body>
</html>
The contents of that div
will be replaced with Hello World!
.
This is useful because you can control exactly where to insert the value and what it should look like.
Conclusion
In this post, we looked at three different wants you can get a variable in your JavaScript to show up on the page.
You can either use alert()
, document.write()
, or innerHTML
, each of which have their own advantages and disadvantages.
Thanks for reading and we hope this has been helpful!
- Getting Started with Express
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Using Push.js to Display Web Browser Notifications
- How To Create a Modal Popup Box with CSS and JavaScript