HTML documentsis a powerful scripting language that allows you to manipulate and display content in your HTML documents. One of the most common tasks when working with JavaScript is to use variables to store and manage data. In this tutorial, we will learn how to use JavaScript variables in HTML.
Basic Usage
To use a JavaScript variable in HTML, you can simply include it within the HTML using the <script>
tag. Here’s a simple example:
<script> var message = "Hello, World!"; document.write(message); </script>
In this example, we declare a JavaScript variable called message and assign it the value “Hello, World!”. We then use the document.write() method to insert the contents of the variable into the HTML document. The output of this code will be:
Hello, World!
Display JavaScript Variables in HTML Elements
To display a JavaScript variable inside an HTML element, you can use the innerHTML property of the element. Here’s an example:
<script> var myVar = "Hello, World!"; document.getElementById("demo").innerHTML = myVar; </script>
In this example, we assign the value “Hello, World!” to a JavaScript variable called myVar. We then use the getElementById() method to find an HTML element with the ID “demo” and set its innerHTML property to the value of myVar. This will display the contents of the variable inside the specified HTML element.
Using JavaScript Variables with HTML Attributes
JavaScript variables can also be used to modify the attributes of HTML elements. For example, suppose we have an image element with the following HTML code:
<img id="myImg" src="example.jpg" alt="Example Image">
We can use JavaScript to change the src attribute of the image element like this:
<script> var newSrc = "new-image.jpg"; document.getElementById("myImg").src = newSrc; </script>
In this example, we assign the value “new-image.jpg” to a JavaScript variable called newSrc. We then use the getElementById() method to find the image element with the ID “myImg” and set its src attribute to the value of newSrc. This will change the image displayed by the HTML element.
Conclusion
Using JavaScript variables in HTML is a powerful way to manipulate and display content on your web pages. By understanding how to declare, assign, and use variables in HTML, you can create dynamic and interactive web applications. This tutorial has given you a basic understanding of how to use JavaScript variables in HTML, and you can now apply these concepts to your own projects.