Skip to content

Use JavaScript variable in HTML attribute | Example code

  • by

Use getElementById to show JavaScript variables in the HTML attribute. This method will show variable values in a particular HTML element.

var tbIndx = 10;
document.getElementById("someInput").value = tbIndx;

Using document.write() method, innerHTML property or window.alert() method other ways to display JavaScript variable values in HTML pages:

Use JavaScript variable in HTML attribute

Simple example code set the JS variable value into input HTML.

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="someInput" name="someInput"></input>

  <script type="text/javascript">

   var tbIndx = 10;
   document.getElementById("someInput").value = tbIndx;
   
 </script>

</body>
</html>

Output:

Use JavaScript variable in HTML attribute

Using document.write() method

This method allows you to replace the entire content of the HTML <body> tag.

let name = "Hello...";
document.write(name); 

Using innerHTML property

The innerHTML property holds the content of that element. use document.getElementById method to retrieve it and change its innerHTML property.

<body>
  <h1>Hello, my name is <span id="name"></span></h1>
  <script>
    let name = "John";
    document.getElementById("name").innerHTML = name;
  </script>
</body>

Using window.alert() method

The window.alert() method allows you to launch a dialog box at the front of your HTML page.

<body>
  <h1>Hello World</h1>
  <script>
    window.alert("Greetings");
  </script>
</body>

Do comment if you have any doubts or suggestions on this Js variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading