How To Javascript Variable In Html

In this blog post, we will learn how to use JavaScript variables in HTML to make our web pages more dynamic and interactive. This will help you to create more engaging user experiences by injecting data directly into the HTML structure.

1. Using JavaScript variables in HTML with document.write()

Using document.write() method is the simplest way to display JavaScript variables directly in your HTML document. This method writes a string of text or a variable value to the HTML document where the JavaScript code is placed.

Here’s an example:

<html>
<body>
    <script>
        var message = "Welcome to our website!";
        document.write(message);
    </script>
</body>
</html>
    

In this example, the JavaScript variable message contains a string “Welcome to our website!”, and we are using document.write() to display it in the HTML document.

2. Using JavaScript variables in HTML with innerHTML

The innerHTML property is another way to use JavaScript variables in your HTML document. This property allows you to set or retrieve the HTML content of an element. You can use this property to insert your JavaScript variable into an HTML element.

Here’s an example:

<html>
<body>
    <p id="example"></p>
    <script>
        var message = "Welcome to our website!";
        document.getElementById("example").innerHTML = message;
    </script>
</body>
</html>
    

In this example, we have an HTML paragraph element with an ID of “example”. We are using the innerHTML property to set the content of this paragraph with the value of the message variable.

3. Using JavaScript variables in HTML with DOM manipulation

DOM (Document Object Model) manipulation is a more advanced technique that offers even greater flexibility in using JavaScript variables in your HTML document. This involves creating, modifying, or removing HTML elements directly using JavaScript.

Here’s an example:

<html>
<body>
    <ul id="list"></ul>
    <script>
        var fruits = ["Apple", "Banana", "Cherry"];
        var list = document.getElementById("list");

        for (var i = 0; i < fruits.length; i++) {
            var listItem = document.createElement("li");
            listItem.textContent = fruits[i];
            list.appendChild(listItem);
        }
    </script>
</body>
</html>
    

In this example, we have an unordered list element with an ID of “list” and a JavaScript array of fruits. We are using DOM manipulation to create and insert list items for each fruit in the array.

Conclusion

As demonstrated in this blog post, there are several ways to use JavaScript variables in your HTML documents. Depending on your requirements, you can choose any of these methods to create dynamic and interactive web pages. By combining JavaScript with HTML, you can create more engaging user experiences and make your website stand out from the crowd.