I've made a toy example (counter) and I wanted to display the output on an html page. I found that the javascript code only works when div is "declared" before javascript code. I thought the order of calling the div doesn't matter.
here is the simple code below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Random Variable 3</title>
</head>
<body>
<!-- div here (before js code) is working -->
<div id="content2display1"; style="text-align: center; font-size: 80px;"></div>
<script>
let x = 0;
function getRandom1() {
x = x 1
document.getElementById('content2display1').innerHTML = x; // content2display che viene mandato a html
console.log("x: ", x)
// return rv_i;
};
getRandom1();
setInterval("getRandom1();", 1000);
</script>
<!-- div here is not working... -->
<!-- <div id="content2display1"; style="text-align: center; font-size: 80px;"></div> -->
</body>
</html>
Why the code doesn't work when div is after the javscript code?
CodePudding user response:
If you put your script before the div declaration, the div itself doesn't exist yet in the DOM and your "document.getElementById" returns null.
If you want to put your script before, you should wrap your script body into a DOMContentLoaded listener:
document.addEventListener('DOMContentLoaded', () => {
//your script here
});
Doing so, the script waits for the entire DOM to be loaded before to be executed.