HTML is now even advancing in several frameworks in web development that make life easier for developers. However, there are several functions of JavaScript utilized in HTML to make websites more attractive. When an object is loaded into HTML, the onload property is activated. This will run the script each time the corresponding element loads. The window onload event is set off whenever a successful web page launch occurs.
This write-up will explain the method for using this JavaScript variable in HTML.
How to Use this JavaScript Variable in HTML?
To use this JavaScript variable in HTML, try out the given instructions.
Step 1: Create “div” Container
First, create a “div” container with the help of the “<div>” tag. Also, insert an “id” attribute and assign a name to the id inside the “div” opening tag:
Step 2: Define JavaScript Function
In the “<script>” element, we will specify the following code:
window.onload = function() {
var fname = prompt("what is your name?");
var lengthOfName = fname.length
document.getElementById('result').innerHTML = lengthOfName;
};
</script>
In the above-stated snippet:
-
- First, define “window.onload” function that is called when the window will reload.
- Next, initialize a variable with the name that will appear on the window after loading.
- “var lengthOfName” is utilized to calculate the length of the entered name.
- “document.getElementById().innerHTML” will return the HTML element as a JavaScript object which has the pre-defined property innerHTML. The “innerHTML” property contains the content of the HTML tag.
It can be observed that the current object is accessed, and the length of its innerHTML value has been displayed:
That’s all about using this JavaScript variable in HTML.
Conclusion
To use this JavaScript variable in HTML, define the “window.onload” function that is called when the window reloads. After that, initialize the variables “fname” and “lengthOfName” to calculate the length of the entered name. The “document.getElementById().innerHTML” will return the html element as a JavaScript object which has the pre-defined property innerHTML. This post explained about using this JavaScript variable in HTML.