I am simply trying to run a javascript that will create a "grid" table for me. Here's my code...
<!DOCTYPE html>
<html>
<head>
<style>
* {margin: 0;}
body {width: 100%; height: 100%;}
table {margin: 20px auto; border-collapse: collapse;}
td {border: thin solid black; height: 5px; width: 5px;}
</style>
</head>
<body>
<table>
<script>
var x = 1;
var y = 1;
while (x < 10) {
document.write("<tr>");
while (y < 10) {
document.write("<td></td>");
y++;
}
document.write("</tr>");
x++;
}
</script>
</table>
</body>
When I run this, the nested WHILE loop works but the first one only runs once giving me one row of 9 blocks.
However if I comment out the nested loop and add in a simple output to make it look like...
<script>
var x = 1;
while (x < 10) {
document.write("<tr>");
document.write("<td></td>");
document.write("</tr>");
x++;
}
</script>
It will correctly print out 1 column of 9 rows... what am I missing??
Thanks.
You have to reset your y-variable after the y-loop finishes, else it will never enter the loop after the first time if exits the loop.
Though, I would recommend using for loops, since those are more appropriate for your case.
Also note that every time you use the
document.write
method, the browser will have to reparse your whole DOM, which is not good for performance.