How to Use JavaScript Variable in HTML

Anika Tabassum Era Feb 02, 2024
  1. JavaScript User Defined Variable Usage in HTML
  2. JavaScript Variable Loaded From Prompt
  3. Create a Tag Element From Script and Variable Access to HTML
How to Use JavaScript Variable in 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:

user defined js variable in html

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:

prompt input

prompt input to html

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:

create tag element to pass in html

create tag element to pass in html2

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Variable