A2oz

How to Access JavaScript Variables in HTML?

Published in JavaScript 2 mins read

You can access JavaScript variables in HTML using the innerHTML property or by creating data attributes.

Using innerHTML

  1. Declare a JavaScript variable:
    let myVariable = "Hello from JavaScript!";
  2. Select an HTML element:
    let myElement = document.getElementById("myElement");
  3. Set the innerHTML property of the element to the JavaScript variable:
    myElement.innerHTML = myVariable;

This will display the value of the variable within the HTML element.

Using Data Attributes

  1. Add a data attribute to your HTML element:
    <div id="myElement" data-message="This is a message from a data attribute."></div>
  2. Access the data attribute value in JavaScript:
    let myElement = document.getElementById("myElement");
    let message = myElement.dataset.message;
  3. Use the data attribute value in your HTML:
    myElement.innerHTML = message;

This method allows you to store and retrieve data directly from the HTML element without needing to modify the element's content.

Example:

<!DOCTYPE html>
<html>
<head>
<title>Accessing JavaScript Variables in HTML</title>
</head>
<body>

<div id="myElement"></div>

<script>
let myVariable = "Hello from JavaScript!";
let myElement = document.getElementById("myElement");
myElement.innerHTML = myVariable;
</script>

</body>
</html>

This code will display "Hello from JavaScript!" inside the div element with the ID "myElement".

Remember: Always ensure your JavaScript code is executed after the HTML element is loaded to avoid errors.

Related Articles