Lukas Baliƫnas Lukas Baliƫnas - 3 months ago 12
HTML Question

Naming variables in for loop

I'm new to JS and HTML. I learned that it's possible to name a variable by code. So i tried some simple variable naming code. However, it doesn't print anything on the page.

What seems to be the problem?

javascript


for (var i = 0; i < 10; i++) {
window['var' + i] = i;
}
document.getElementById("text").innerHTML = "" + var8;


html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="JScript.js"></script>
<title>Practice</title>
</head>
<body>
<p><span id="text"></span>left</p>
</body>
</html>

Answer

Enclose your javascript code in below document.ready function, so that it will execute only when your page is ready.

$(document).ready(function () {
    // enter your code here
});
Comments