Is it possible to generate a random number from JavaScript to HTML using button onclick but return it through a <div> ? I have looked at other similar questions but they all seem to use either <input> or <form>. I am not getting any errors in my browser, when I try this code but the output is coming from the <div> saying 'undefined' as opposed to a number so I'm obviously not defining number but I'm just a bit confused by JavaScripts syntax.
/// HTML ///
<html>
<head>
<script type="text/javascript" src="randRandomScript.js">
</script>
</head>
<body>
<button name="randNumberButton" onclick="randNumberScript()" >Click for Number</button>
<div id="number"></div>
</body>
</html>
/// JavaScript ///
var randomNumberObject = math.floor(math.random()*10);
function randNumberScript () {
document.getElementById("number").innerHTML = randomNumberObject;
}
.textContentthan.innerHTML.textContentdoesn’t try to interpret the string as HTML, so it runs faster, and it will let you include characters like<>.innerHTMLis a convenient way to insert multiple HTML elements inside an element, such asthe secret numbers are <b>5</b> and <b>7</b>. It can be a quick way to test some code to set element contents, but usually you should use other methods once you understand the structure you want. The problem withinnerHTMLis that if the string you are assigning contains user input, for example if the user typed in5and7, then the user could type HTML like<h1>5</h1>and mess up the page.