How to display JavaScript variables in an HTML page without document.write?

Use Element.innerHTML in JavaScript to display JavaScript variables in an HTML page without document.write(). This approach provides better control over content placement and doesn't overwrite the entire page.

Basic Example: Displaying Variables

Here's how to display JavaScript variables using innerHTML:

<!DOCTYPE html>
<html>
<head>
    <title>Display Variables</title>
</head>
<body>
    <h2>User Information</h2>
    <p>Name: <span id="name"></span></p>
    <p>Age: <span id="age"></span></p>
    <p>City: <span id="city"></span></p>

    <script>
        // JavaScript variables
        let userName = "John Smith";
        let userAge = 28;
        let userCity = "New York";

        // Display variables using innerHTML
        document.getElementById("name").innerHTML = userName;
        document.getElementById("age").innerHTML = userAge;
        document.getElementById("city").innerHTML = userCity;
    </script>
</body>
</html>

Interactive Example: Input Field

Display user input dynamically as they type:

<!DOCTYPE html>
<html>
<head>
    <title>Interactive Display</title>
</head>
<body>
    <h2>Live Text Display</h2>
    <input type="text" class="name" placeholder="Enter your name">
    <p>You typed: <strong class="jsValue"></strong></p>

    <script>
        var myName = document.querySelector('.name');
        var jsValue = document.querySelector('.jsValue');

        myName.addEventListener('input', function(event) {
            jsValue.innerHTML = myName.value;
        }, false);
    </script>
</body>
</html>

Using textContent vs innerHTML

For plain text, consider textContent as a safer alternative:

<!DOCTYPE html>
<html>
<head>
    <title>textContent vs innerHTML</title>
</head>
<body>
    <p>Using innerHTML: <span id="html-output"></span></p>
    <p>Using textContent: <span id="text-output"></span></p>

    <script>
        let message = "<b>Hello World</b>";
        
        document.getElementById("html-output").innerHTML = message;
        document.getElementById("text-output").textContent = message;
    </script>
</body>
</html>

Comparison

Method Use Case Security
innerHTML HTML content Risk of XSS attacks
textContent Plain text only Safe from XSS
document.write() Legacy approach Overwrites entire page

Conclusion

Use innerHTML to display JavaScript variables in HTML elements. For plain text, prefer textContent for better security. Both methods provide better control than document.write().

Updated on: 2026-03-15T23:18:59+05:30

572 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements