How to Use JavaScript Variable in HTML
- JavaScript User Defined Variable Usage in HTML
- JavaScript Variable Loaded From Prompt
- Create a Tag Element From Script and Variable Access to HTML
JavaScript variables are often user-defined while coding, or you can use prompt to fetch data and store it in a variable for further use.
Here, we will show how to act upon a user-defined variable and use it in HTML, and the later demonstration will explain how the prompt can help us in this regard.
JavaScript User Defined Variable Usage in HTML
We are using jsbin
for the code examples, and here you will see the p
element is identified by the id output
. Initially, the variable myPet
is set to be Tobey
, and the later simple line was executed in the webpage. getElementById
finds the preferred id
, and later the variables are passed in the inner.HTML
format so the JavaScript variables can be used in the HTML
.
Code Snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<style>
p{
background: pink;
}
</style>
</head>
<body>
<p id="output"></p>
</body>
</html>
var myPet = 'Tobey';
var nameLength = myPet.length;
document.getElementById('output').innerHTML =
myPet + ' is a ' + nameLength + ' letter name!';
Output:
JavaScript Variable Loaded From Prompt
In this segment, we will see how we easily input value in the prompt window, and that directly is displayed in our loaded webpage.
Code Snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<style>
p{
background: pink;
}
</style>
</head>
<body>
<p id="output"></p>
</body>
</html>
var myPet = prompt();
var nameLength = myPet.length;
document.getElementById('output').innerHTML =
myPet + ' is a ' + nameLength + ' letter name!';
Output:
Create a Tag Element From Script and Variable Access to HTML
Here, we will create a p
tag in the script, which will be accessible in the HTML body
. The p.innerHTML
is the key to passing the variable data towards the body
tag.
Code Snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<style>
p{
background: gray;
color: white;
text-align: center;
}
</style>
</head>
<body>
</body>
</html>
var myPet = prompt('Enter Name');
var nameLength = myPet.length;
p = document.createElement('p');
p.innerHTML = myPet + ' is a ' + nameLength + ' letter name!';
document.body.appendChild(p);
Output:
Related Article - JavaScript Variable
- How to Access the Session Variable in JavaScript
- How to Check Undefined and Null Variable in JavaScript
- How to Mask Variable Value in JavaScript
- Why Global Variables Give Undefined Values in JavaScript
- How to Declare Multiple Variables in a Single Line in JavaScript
- How to Declare Multiple Variables in JavaScript