How to Use Javascript Variable in HTML
You can only use Javascript variable in HTML by linking the Javascript variable to a HTML element using an id
or class
attribute.
Linking Javascript Variable to HTML Element
- Create an element in HTML.
Code
<p>Content is loading ...</p>
Assign an id to the element.
Code
<p id="content-holder">Content is loading ...</p>
If you check this now all you will see is:
You can now add Javascript to your page using script tags.
<script>
// Write your Javascript code inside here
</script>
Now, you can start working on the Javascript. Create your Javascript Variable.
Code
var newContent = "This content will be loaded as a paragraph on the p tag when we add it through Javascript.";
You grab the element in Javascript using the assigned id value.
Code
var contentHolder = document.getElementById('content-holder');
To display the variable in HTML, assign the variable to the element in Javascript using the innerHTML property.
Code
contentHolder.innerHTML = newContent;
Result
Complete Code
<p id="content-holder">Content is loading ...</p>
<script>
// Write your Javascript code inside here
var newContent = "This content will be loaded as a paragraph on the p tag when we add it through Javascript.";
var contentHolder = document.getElementById('content-holder');
contentHolder.innerHTML = newContent;
</script>
You can use the above method for string and number variables.
Using Javascript Array Variable in HTML
To view array and object variables in HTML, you have to loop through the items in Javascript before passing them to HTML.
Example
<ul id="shopping-list"></ul>
<script>
var shoppingitems = ["soap", "toothpaste", "tissue", "toothbrush"];
var shoppinglist = document.getElementById('shopping-list');
for (var n=0; n<shoppingitems.length; n++) {
shoppinglist.innerHTML += `<li>${shoppingitems[n]}</li>`;
}
</script>
Results
You can also interact with the code for this project.