How to display JavaScript values in HTML

Updated onbyAlan Morel
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.

JAVASCRIPT
alert("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.

JAVASCRIPT
document.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:

JAVASCRIPT
const 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.

JAVASCRIPT
const 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.