Categories
JavaScript Answers

How to display a JavaScript variable in HTML body?

Spread the love

Sometimes, we want to display a JavaScript variable in HTML body.

In this article, we’ll look at how to display a JavaScript variable in HTML body.

How to display a JavaScript variable in HTML body?

To display a JavaScript variable in HTML body, we set the innerHTML property of the element.

For instance, we write

<h1>"The value for number is: " <span id="myText"></span></h1>

to add some elements.

Then we write

const number = "123";
document.getElementById("myText").innerHTML = number;

to select the span with getElementById and then set its innerHTML property to number to render number in the span.

Conclusion

To display a JavaScript variable in HTML body, we set the innerHTML property of the element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *