When working with JavaScript, there are times you want to access the value of a JavaScript variable from within your HTML code. In this blog post, we will discuss a few methods to accomplish this task.
1. Using the document.write() method
The document.write() method writes a string of text to the document. You can use this method to output a JavaScript variable into your HTML.
Let’s say you have a variable called myVar in your JavaScript code:
<script> var myVar = "Hello, World!"; </script>
To output the value of myVar in your HTML, use the following code:
<script> document.write(myVar); </script>
2. Using the innerHTML property
You can also use the innerHTML property to set or get the HTML content inside an HTML element. To use this method, first, create an HTML element with a unique ID:
<div id="output"></div>
Next, use JavaScript to set the innerHTML property of the element:
<script> var myVar = "Hello, World!"; document.getElementById("output").innerHTML = myVar; </script>
3. Using JavaScript template literals
JavaScript template literals are a more modern way to embed JavaScript variables into HTML markup. They are denoted by backticks (`) and make it easy to include variables using the ${variableName} syntax.
For example, you can create an HTML template using a variable like this:
<script> var myVar = "Hello, World!"; var template = `<div>${myVar}</div>`; document.body.innerHTML += template; </script>
Conclusion
In this blog post, we covered three different methods to get JavaScript variables in HTML: using the document.write() method, the innerHTML property, and JavaScript template literals. Each method has its use cases and can be helpful when working with JavaScript and HTML.