user2327103
user2327103

Reputation: 21

Making text with variables for JS?

I have a variable that makes a random number from 0 - 20. I wanted it to show up on screen so i did document.write(variable). When i run it the whole page is blank except for the variable. How do you make the variable show up in the screen without having your page destroyed or something. Thank You!

Upvotes: 0

Views: 63

Answers (2)

fardjad
fardjad

Reputation: 20394

Don't use document.write.

Select a DOMElement and set it's text or innerHTML to your random generated number.

for example:

<!DOCTYPE HTML>
<title>Example</title>
<div id="random"></div>
<script>
    var n = String(yourRandomGeneratedNumber);
    document.getElementById('random').innerHTML = n;
</script>

PS: the HTML is valid!

Upvotes: 2

Brian McCutchon
Brian McCutchon

Reputation: 8584

If you use document.write() after your page is loaded, it will overwrite the HTML document. You can only use this command in the output stream.

Upvotes: 2

Related Questions